Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

The Error trait is used by the standard library and most crates for their error types.

To implement the Error trait for a custom error we need to implement the Debug and Display traits:

  1. The Debug implementation can be done using the derive() macro.

  2. The Display implementation must be done manually.

  3. The Error implementation must just be declared, there is no method to implement.

First, we import the Error trait and the fmt (i.e.: format) module:

We declare a custom error, using here a struct with a single message field, but an enum would do also. Note the implementation of the Debug trait through the derive attribute:

We then implement the Display formatter trait that will allow to print our error through the print!() and format!() macros:

Finally, we implement the Error trait, which requires no method definition:

Now we can define an example function that returns a Result that uses our custom error:

Here is a usage of the foo() function with two different values:

My error message.
2.2
()