Created
January 18, 2019 03:14
-
-
Save nyinyithann/c708fda5d58d1dc990cce3c20ebecdfa to your computer and use it in GitHub Desktop.
Print error and its source
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::error::Error; | |
use std::fs::File; | |
use std::io; | |
use std::io::prelude::*; | |
use std::io::{stderr, Write}; | |
fn main() { | |
let r = read_file("wrong.test"); // read_file(r"/Users/nyinyithan/Downloads/test.json"); | |
match r { | |
Ok(txt) => println!("{}", txt), | |
Err(e) => print_error(&e), | |
} | |
} | |
fn read_file(file_name: &str) -> io::Result<String> { | |
let mut f = File::open(file_name)?; | |
let mut text = String::new(); | |
f.read_to_string(&mut text).map(|x| x.to_string())?; | |
Ok(text) | |
} | |
fn print_error(mut error: &dyn Error) { | |
let _ = writeln!(stderr(), "error: {}", error); | |
while let Some(e) = error.source() { | |
let _ = writeln!(stderr(), "caused by: {}", e); | |
error = e; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment