pub struct Error { /* private fields */ }Expand description
The error type used by the library.
Errors generally form a chain, with higher-level errors typically
providing additional context for lower level ones. E.g., an IO error
such as file-not-found could be reported by a system level API (such
as std::fs::File::open) and may be contextualized with the path
to the file attempted to be opened.
use std::fs::File;
use std::error::Error as _;
let path = "/does-not-exist";
let result = File::open(path).with_context(|| format!("failed to open {path}"));
let err = result.unwrap_err();
assert_eq!(err.to_string(), "failed to open /does-not-exist");
// Retrieve the underlying error.
let inner_err = err.source().unwrap();
assert!(inner_err.to_string().starts_with("No such file or directory"));For convenient reporting, the Display representation takes care
of reporting the complete error chain when the alternate flag is
set:
// > failed to open /does-not-exist: No such file or directory (os error 2)
println!("{err:#}");The Debug representation similarly will print the entire error
chain, but will do so in a multi-line format:
// > Error: failed to open /does-not-exist
// >
// > Caused by:
// > No such file or directory (os error 2)
println!("{err:?}");On top of that, if the backtrace feature is enabled, errors may also
contain an optional backtrace. Backtrace capturing behavior follows the
exact rules set forth by the std::backtrace module. That is, it is
controlled by the RUST_BACKTRACE and RUST_LIB_BACKTRACE environment
variables. Please refer to this module’s documentation for precise
semantics, but in short:
- If you want panics and errors to both have backtraces, set
RUST_BACKTRACE=1 - If you want only errors to have backtraces, set
RUST_LIB_BACKTRACE=1 - If you want only panics to have backtraces, set
RUST_BACKTRACE=1andRUST_LIB_BACKTRACE=0