Rust Reference ยท Standard Library Modules
The std::error module
Reference for Rust std::error: the Error trait, source chains, Box<dyn Error>, downcasting and writing custom error types that work with the ? operator.
std::error contains a single central item: the Error trait. A type that implements Error says "I am an error value": it can be printed for users (Display), shown to developers (Debug), and optionally point at the lower-level error that caused it through source(). Because the trait is an object-safe standard contract, you can store any error as Box<dyn Error> and pass it around without naming its type.
Implementing Error only requires that the type already implements Debug and Display; every method of the trait has a default. The ? operator uses From to convert errors, and the standard library provides From<E: Error> for Box<dyn Error> as well as From<&str> and From<String>.
use std::error::Error; fn run() -> Result<(), Box<dyn Error>> { let n: i32 = "42".parse()?; println!("{n}"); Ok(()) }
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 }
| Item | Description |
|---|---|
source() |
The underlying error, if any. Walk the chain by calling it repeatedly. |
description(), cause() |
Deprecated; implement Display and source instead. |
dyn Error methods |
is::<T>(), downcast_ref::<T>(), downcast_mut::<T>(). |
Box<dyn Error> |
downcast::<T>() returns Result<Box<T>, Box<dyn Error>>. |
Box<dyn Error + Send + Sync> |
The thread-safe variant; also converts from &str and String. |
Usage notes
Displayis for people,Debugfor developers. KeepDisplaymessages short and lower case without a trailing period; they are often embedded in longer messages.- Do not repeat the source in
Display. Return it fromsource()and let the reporter print the chain. Box<dyn Error>is great for binaries and quick scripts, but libraries should return a concrete error type so callers can match on it.maincan returnResult<(), Box<dyn Error>>; anErris printed withDebugand the process exits with code 1.- Downcasting needs
'static. Errors that borrow data cannot be downcast. Errorlives incoretoo (since Rust 1.81), sono_stdcrates can implement it.Send + Sync: useBox<dyn Error + Send + Sync>when errors cross threads, for example fromthread::spawnresults.?needsFrom: converting a specific error intoBox<dyn Error>works for anyE: Error, butBox<dyn Error>itself does not implementError.
Related
Result<T, E>,?operator,std::convert,std::num- Lessons: Custom errors, Error design, Result