Creating a custom error type
Rust has a trait to unify propagating errors by providing the std::error::Error
trait. Since the Error
trait is defined as pub trait Error: Debug + Display
, any type that implements Error
should also implement the Debug
and Display
traits.
Let's see how we can create a custom error type by creating a new module:
- In
src/lib.rs
, add the newerrors
module:pub mod errors;
- After that, create a new folder,
src/errors
, and add thesrc/errors/mod.rs
andsrc/errors/our_error.rs
files. Insrc/errors/mod.rs
, add this line:pub mod our_error;
- In
src/errors/our_error.rs
, add the custom type forerror
:use rocket::http::Status; use std::error::Error; use std::fmt; #[derive(Debug)] pub struct OurError { pub status: Status, pub message: String, debug: Option<Box<dyn Error>>, } impl fmt::Display for OurError { fn fmt(&self, f: &mut fmt...