O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Custom errors and the Error trait

Quite often, we wish to separate the errors our programs might make from every other one. This is typically done in other languages by creating a new subclass of some exception based class, and possibly overriding some of the parent's methods.

Rust's approach is similar, but since we don't have classes or objects really, we use traits and implementations. Here's the Error trait from the standard library:

pub trait Error: Debug + Display + Reflect {     fn description(&self) -> &str;     fn cause(&self) -> Option<&Error> { None } } 

So, the new error type we're about to write requires these two methods. The description method returns a string slice reference, which tells in free form what the error is about. The ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required