On this page
Error
Prev: `Display` | Up: error_and_fmt | Next: `format`
Rel: error_and_fmt, rust/builtins
Ref: Rust std — Error
Tags: #public #prog #rust #stdlib #error_and_fmt #tier/core
Signature & Overview
trait Error: Debug + Display { fn source(&self) -> Option<&(dyn Error + 'static)> }
Standard trait for composable error types (Box<dyn Error> or custom error enums).
Notes & Pitfalls
- Requires both
DebugandDisplay: Overridesource(&self)when wrapping an underlying cause so error chains stay inspectable. - Pair with
thiserror(libraries) oranyhow(apps) to eliminate boilerplate in larger codebases.
Example
use std::{error::Error, fmt};
#[derive(Debug)]
struct ParseError(&'static str);
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) }
}
impl Error for ParseError {}
fn main() {
let err: Box<dyn Error> = Box::new(ParseError("empty input"));
assert_eq!(err.to_string(), "empty input");
}
Linked from
Related notes
- tuts/rust/std/error_and_fmt/Display Linked here; links to this page; shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/error_and_fmt/format Linked here; links to this page; shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/error_and_fmt Linked here; links to this page; shared tags: #prog, #rust, #stdlib
- tuts/rust/builtins Linked here; shared tags: #prog, #rust
- tuts/rust/std/collections/BinaryHeap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/BTreeMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashSet shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/VecDeque shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/ffi/CString shared tags: #prog, #rust, #stdlib, #tier