This is a reference to help answer this question: โwhat will my Rust program print if something goes wrong?โ
The examples were compiled with Rust 1.76.0. All output in these examples goes to stderr, nothing goes to stdout.
Setup code for thiserror
#[derive(Debug, thiserror::Error)] enum CustomError { #[error("bad thing: {0}")] BadThing(#[from] std::io::Error), } fn make_error() -> Result<(), CustomError> { Ok(std::fs::remove_file("/this/file/does/not/exist")?) }
Debug
fn main() { eprintln!("{:?}", make_error().unwrap_err()) }
BadThing(Os { code: 2, kind: NotFound, message: "No such file or directory" })
Display
fn main() { eprintln!("{}", make_error().unwrap_err()) }
bad thing: No such file or directory (os error 2)
Alternate Display
fn main() { eprintln!("{:#}", make_error().unwrap_err()) }
bad thing: No such file or directory (os error 2)
Unwrap
fn main() { make_error().unwrap(); }
thread 'main' panicked at src/bin/thiserror_unwrap.rs:12:18: called `Result::unwrap()` on an `Err` value: BadThing(Os { code: 2, kind: NotFound, message: "No such file or directory" }) note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Expect
fn main() { make_error().expect("oh no"); }
thread 'main' panicked at src/bin/thiserror_expect.rs:12:18: oh no: BadThing(Os { code: 2, kind: NotFound, message: "No such file or directory" }) note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Return
fn main() -> Result<(), CustomError> { make_error() }
Error: BadThing(Os { code: 2, kind: NotFound, message: "No such file or directory" })