update example error handling
- Add error-chain dev dependency - Add error handling using `?` instead of `unwrap`
This commit is contained in:
@@ -22,3 +22,4 @@ libflate = "0.1.5"
|
||||
[dev-dependencies]
|
||||
env_logger = "0.4"
|
||||
serde_derive = "1.0"
|
||||
error-chain = "0.10"
|
||||
|
||||
@@ -1,15 +1,24 @@
|
||||
// cargo run --example response_json
|
||||
//! `cargo run --example response_json`
|
||||
extern crate reqwest;
|
||||
#[macro_use] extern crate serde_derive;
|
||||
#[macro_use] extern crate error_chain;
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
error_chain! {
|
||||
foreign_links {
|
||||
ReqError(reqwest::Error);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Response {
|
||||
origin: String,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut res = reqwest::get("https://httpbin.org/ip").unwrap();
|
||||
println!("JSON: {:?}", res.json::<Response>());
|
||||
fn run() -> Result<()> {
|
||||
let mut res = reqwest::get("https://httpbin.org/ip")?;
|
||||
let json = res.json::<Response>()?;
|
||||
println!("JSON: {:?}", json);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
quick_main!(run);
|
||||
|
||||
@@ -1,17 +1,31 @@
|
||||
//! `cargo run --example simple`
|
||||
extern crate reqwest;
|
||||
extern crate env_logger;
|
||||
#[macro_use] extern crate error_chain;
|
||||
|
||||
fn main() {
|
||||
env_logger::init().unwrap();
|
||||
error_chain! {
|
||||
foreign_links {
|
||||
ReqError(reqwest::Error);
|
||||
IoError(std::io::Error);
|
||||
}
|
||||
}
|
||||
|
||||
fn run() -> Result<()> {
|
||||
env_logger::init()
|
||||
.expect("Failed to initialize logger");
|
||||
|
||||
println!("GET https://www.rust-lang.org");
|
||||
|
||||
let mut res = reqwest::get("https://www.rust-lang.org").unwrap();
|
||||
let mut res = reqwest::get("https://www.rust-lang.org")?;
|
||||
|
||||
println!("Status: {}", res.status());
|
||||
println!("Headers:\n{}", res.headers());
|
||||
|
||||
::std::io::copy(&mut res, &mut ::std::io::stdout()).unwrap();
|
||||
// copy the response body directly to stdout
|
||||
let _ = std::io::copy(&mut res, &mut std::io::stdout())?;
|
||||
|
||||
println!("\n\nDone.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
quick_main!(run);
|
||||
|
||||
Reference in New Issue
Block a user