-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Description
What it does
Libraries regularly implement their own error types, frequently as enum
wrappers around dependency-specific errors.
Other libraries like anyhow exist to make error handling in application code simpler, at least for error types that implement std::error::Error
.
However, when wrapping/writing custom error types for a library, it's easy to forget to implement std::error::Error
. It would be nice to have a clippy
lint that detects custom error types and suggests that the user add an impl std::error::Error for MyError {}
implementation.
Categories (optional)
Potentially clippy::style
.
What is the advantage of the recommended code over the original code
The recommended code transitively simplifies error handling in other codebases by ensuring that the standard Error
trait is implemented. This enables more direct use of libraries like anyhow
.
Drawbacks
This lint should only be run on crates that are specified as libraries, not as application code (i.e., producing binaries).
It might also be somewhat difficult to determine which types are custom error types. Some ideas:
- Look for
Result<T, X>
, whereX
is a crate-local type - Look for types within
crate::*::error
that match a naming pattern (like*Error*
) - Look for
enum
types whose variants' associated datas contain one or more implementations ofstd::error::Error
Example
pub enum MyError {
Io(std::io::Error),
Other(SomeOtherError),
}
Could be written as:
pub enum MyError {
Io(std::io::Error),
Other(SomeOtherError),
}
impl std::error::Error for MyError {
// trait impl...
}