Rust Reference ยท Core Traits
The std::error::Error trait
Reference for Rust std::error::Error: implementing it with Display and Debug, source() chains, Box<dyn Error>, the ? operator conversions and downcasting.
std::error::Error is the common interface for error types. It requires Debug + Display as supertraits and offers an optional source() method that returns the underlying cause. Because all errors share one trait, code can accept Box<dyn Error> and report any failure without naming its type.
To make your own error type work with the rest of the ecosystem, implement Display (the message for humans), derive Debug, and write impl Error for MyError {}. If your error wraps another one, override source() so tools can print the whole chain.
impl std::error::Error for ConfigError {}
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub trait Error: Debug + Display { fn source(&self) -> Option<&(dyn Error + 'static)> { None } fn description(&self) -> &str { /* deprecated */ } fn cause(&self) -> Option<&dyn Error> { /* deprecated */ } } impl Error for MyError {} Box<dyn Error> Box<dyn Error + Send + Sync + 'static>
| Item | Description |
|---|---|
Display |
Short, lowercase-by-convention message for users and logs, without the cause text. |
Debug |
Usually #[derive(Debug)]. |
source() |
The wrapped lower-level error, if any. Returns None by default. |
Box<dyn Error + Send + Sync> |
The thread-safe form; it also implements From<&str> and From<String>. |
Errors / panics / edge cases: nothing here panics. description and cause are deprecated; do not implement them.
Usage notes
- Do not repeat the cause in
Display. If you print the source inside your message and also expose it throughsource(), reporters show it twice. ?converts viaFrom.?callsFrom::fromon the error. There is a built-inimpl<E: Error> From<E> for Box<dyn Error>, so?works in functions returningResult<T, Box<dyn Error>>. For your own enum, writeimpl From<ParseIntError> for MyError.Box<dyn Error>itself does not implementError. This avoids conflicting impls; use&dyn Error, or.as_ref(), when passing it to a function that wants&dyn Error.- Prefer
+ Send + Syncfor errors that cross thread boundaries or are stored inanyhow-style types. - Downcasting works through
is::<T>(),downcast_ref::<T>()andBox::downcast::<T>()ondyn Error + 'static, as in the second example. maincan return an error.fn main() -> Result<(), Box<dyn Error>>prints theDebugform of an error and exits with code 1.- Libraries vs applications. Libraries should expose a concrete error enum so callers can match on it; applications often use
Box<dyn Error>for convenience. - Chain printing: the loop in the first example, walking
source(), is the standard way to show every layer.core::error::Erroris theno_stdhome of the same trait.
Related
?operator,Result,Display,Any,FromandInto- Lessons: Custom errors, Error design, Question mark