Skip to content

Instantly share code, notes, and snippets.

@Jwata
Last active October 10, 2018 04:45
Show Gist options
  • Select an option

  • Save Jwata/52c957774a2998815ade918758d78291 to your computer and use it in GitHub Desktop.

Select an option

Save Jwata/52c957774a2998815ade918758d78291 to your computer and use it in GitHub Desktop.
Refactoring error handling in Rust
// main.rs
mod request;
use request::request;
fn main() {
match request() {
Ok(text) => println!("{}", text),
Err(err) => println!("{}", err)
}
}
extern crate reqwest;
use reqwest::StatusCode;
pub fn request() -> Result<String, String> {
match reqwest::get("https://www.rust-lang.org/en-US") {
Ok(mut r) => match r.status() {
StatusCode::OK => match r.text() {
Ok(t) => return Ok(t),
Err(_) => return Err("Failed to extract text from response".to_string())
},
s => return Err(format!("Invalid Status Code: {:?}", s)),
},
Err(_) => return Err("Request Failed".to_string()),
}
}
// main.rs
mod request;
mod error;
use request::request;
fn main() {
match request() {
Ok(text) => println!("{}", text),
Err(err) => println!("{}", err),
}
}
// request.rs
extern crate reqwest;
use error::Error;
type RequestResult<T> = Result<T, Error>;
pub fn request() -> RequestResult<String> {
let mut res =
reqwest::get("http://sample.com/")?;
if !res.status().is_success() {
let err = Error::InvalidStatusCode { code: res.status() };
return Err(err);
}
return Ok(res.text()?);
}
extern crate reqwest;
use std::fmt;
pub enum Error {
HttpError(reqwest::Error),
InvalidStatusCode { code: reqwest::StatusCode },
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::HttpError(ref e) => writeln!(f, "Http Request Failed. {}", e),
Error::InvalidStatusCode { code: c } => writeln!(f, "Invalid Status Code. {}", c),
}
}
}
impl From<reqwest::Error> for Error {
fn from(e: reqwest::Error) -> Error {
Error::HttpError(e)
}
}
@Jwata
Copy link
Author

Jwata commented Oct 10, 2018

01_request.rs is ugly because of the conditional logics. It can be refactored by defining RequestResult as you see in 11_request.rs, so you can use get.(...)?, text(...)? without the error handlings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment