Rust custom error
This crate contains a macro that should make it easier to define custom errors without having to write a lot of boilerplate code.
The custom_error!
macro included in this crate takes a type name
and a list of possible errors and generates a rust enumeration for all the cases,
together with the required impl
blocks implementing std::error::Error
and std::fmt::Display
.
If you only have a single case for an error you can also generate a struct instead of an enum.
You can now write:
extern crate custom_error;
use custom_error;
// Note the use of braces rather than parentheses.
custom_error!
instead of
If you only have a single error case you can also generate a struct:
extern crate custom_error;
use custom_error;
custom_error!
Simple error
To define a simple error, you only have to indicate three things:
- the name of your custom error type,
- the name of the different error cases,
- a human-readable description for each case.
extern crate custom_error;
use custom_error;
custom_error!
Custom error with parameters
You can store data inside your errors. In order to do so, indicate the name and types of the fields to want to store in curly braces after an error type.
extern crate custom_error;
use custom_error;
custom_error!
assert_eq!;
The error messages can reference your parameters using braces ({parameter_name}
).
If you need some custom logic to display your parameters, you can use
advanced custom error messages.
Wrapping other error types
If the cause of your error is another lower-level error, you can indicate that
by adding a special source
field to one of your error cases.
Thus, you can make your custom error wrap other error types, and the conversion from these foreign error types will be implemented automatically.
extern crate custom_error;
use ;
custom_error!
Visibility
You can make an error type public by adding the pub
keyword
at the beginning of the declaration.
custom_error!
Advanced custom error messages
If you want to use error messages that you cannot express with simple formatting strings, you can generate your error messages with custom code.
In the following example, we use this feature to display a different error message based on the cause of the underlying IO error.
custom_error!