Skip to content

Lint idea: suggest std Error trait for custom errors #6409

@woodruffw

Description

@woodruffw

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>, where X 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 of std::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...
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsE-mediumCall for participation: Medium difficulty level problem and requires some initial experience.L-suggestionLint: Improving, adding or fixing lint suggestions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions