Trait error::Error [] [src]

pub trait Error: Debug + Send + Typeable + StdError { }

An extension to std::error::Error which provides dynamic downcasting of errors for use in highly generic contexts.

When to use this trait

In the vast majority of cases, a library-specific enum should be used for cases where there can be many different types of errors. This has the benefit of being very performant and benefiting from all sorts of static checking at both the instantiation site and the handling site of the error.

In other cases, being generic over std::error::Error may be correct - usually for logging errors or in other places where an error is used as input.

Now, a motivating example for this trait, which doesn't fall under either of these cases:

Imagine we are creating a simple web middleware for verifying incoming HTTP requests. It will take in many different user-defined Verifiers and will call them one after the other, rejecting the request on any error.

The first step would be to write a Verifier trait:

pub trait Verifier {
    /// Verify the request, yielding an error if the request is invalid.
    fn verify(&Request) -> Result<(), ???>;

A problem quickly arises - what type do we use for the Err case? We cannot use a concrete type since each Verifier may wish to throw any number of different errors, and we cannot use a generic since the type is chosen by the implementor, not the caller, and it cannot be a generic on the trait since we will want to store many Verifiers together.

Enter: Box<error::Error>, a type which can be used to represent any std::error::Error with the sufficient bounds, and can also be handled later by downcasting it to the right error using either .downcast or the match_error! macro. This type can be used to meet the needs of consumers like Verifier, but should not be used in cases where enums or generics are better suited.


impl Error

Is this Error object of type E?

If this error is E, downcast this error to E, by reference.

impl Error + Send

Is this Error + Send object of type E?

If this error is E, downcast this error to E, by reference.