Skip to content

Instantly share code, notes, and snippets.

@nyinyithann
Created January 18, 2019 03:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyinyithann/c708fda5d58d1dc990cce3c20ebecdfa to your computer and use it in GitHub Desktop.
Save nyinyithann/c708fda5d58d1dc990cce3c20ebecdfa to your computer and use it in GitHub Desktop.
Print error and its source
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