Crate error_chain [] [src]

A library for consistent and reliable error handling

error-chain makes it easy to take full advantage of Rust's powerful error handling features without the overhead of maintaining boilerplate error types and conversions. It implements an opinionated strategy for defining your own error types, as well as conversions from others' error types.

Quick start

If you just want to set up your new project with error-chain, follow the quickstart.rs template, and read this intro to error-chain.

Why error chain?

Principles of error-chain

error-chain is based on the following principles:

Similar to other libraries like error-type and quick-error, this library introduces the error chaining mechanism originally employed by Cargo. The error_chain! macro declares the types and implementation boilerplate necessary for fulfilling a particular error-handling strategy. Most importantly it defines a custom error type (called Error by convention) and the From conversions that let the try! macro and ? operator work.

This library differs in a few ways from previous error libs:

To accomplish its goals it makes some tradeoffs:

Declaring error types

Generally, you define one family of error types per crate, though it's also perfectly fine to define error types on a finer-grained basis, such as per module.

Assuming you are using crate-level error types, typically you will define an errors module and inside it call error_chain!:

mod other_error {
    error_chain! {}
}

error_chain! {
    // The type defined for this error. These are the conventional
    // and recommended names, but they can be arbitrarily chosen.
    //
    // It is also possible to leave this section out entirely, or
    // leave it empty, and these names will be used automatically.
    types {
        Error, ErrorKind, ResultExt, Result;
    }

    // Without the `Result` wrapper:
    //
    // types {
    //     Error, ErrorKind, ResultExt;
    // }

    // Automatic conversions between this error chain and other
    // error chains. In this case, it will e.g. generate an
    // `ErrorKind` variant called `Another` which in turn contains
    // the `other_error::ErrorKind`, with conversions from
    // `other_error::Error`.
    //
    // Optionally, some attributes can be added to a variant.
    //
    // This section can be empty.
    links {
        Another(other_error::Error, other_error::ErrorKind) #[cfg(unix)];
    }

    // Automatic conversions between this error chain and other
    // error types not defined by the `error_chain!`. These will be
    // wrapped in a new error with, in the first case, the
    // `ErrorKind::Fmt` variant. The description and cause will
    // forward to the description and cause of the original error.
    //
    // Optionally, some attributes can be added to a variant.
    //
    // This section can be empty.
    foreign_links {
        Fmt(::std::fmt::Error);
        Io(::std::io::Error) #[cfg(unix)];
    }

    // Define additional `ErrorKind` variants. The syntax here is
    // the same as `quick_error!`, but the `from()` and `cause()`
    // syntax is not supported.
    errors {
        InvalidToolchainName(t: String) {
            description("invalid toolchain name")
            display("invalid toolchain name: '{}'", t)
        }

        // You can also add commas after description/display.
        // This may work better with some editor auto-identation modes:
        UnknownToolchainVersion(v: String) {
            description("unknown toolchain version"), // note the ,
            display("unknown toolchain version: '{}'", v), // trailing comma is allowed
        }
    }
}

Each section, types, links, foreign_links, and errors may be omitted if it is empty.

This populates the module with a number of definitions, the most important of which are the Error type and the ErrorKind type. An example of generated code can be found in the example_generated module.

Returning new errors

Introducing new error chains, with a string message:

fn foo() -> Result<()> {
    Err("foo error!".into())
}

Introducing new error chains, with an ErrorKind:

error_chain! {
    errors { FooError }
}

fn foo() -> Result<()> {
    Err(ErrorKind::FooError.into())
}

Note that the return type is the typedef Result, which is defined by the macro as pub type Result<T> = ::std::result::Result<T, Error>. Note that in both cases .into() is called to convert a type into the Error type; both strings and ErrorKind have From conversions to turn them into Error.

When the error is emitted inside a try! macro or behind the ? operator, the explicit conversion isn't needed; try! will automatically convert Err(ErrorKind) to Err(Error). So the below is equivalent to the previous:

fn foo() -> Result<()> {
    Ok(try!(Err(ErrorKind::FooError)))
}

fn bar() -> Result<()> {
    Ok(try!(Err("bogus!")))
}

The bail! macro

The above method of introducing new errors works but is a little verbose. Instead we can use the bail! macro, which, much like try! and ?, performs an early return with conversions. With bail! the previous examples look like:

fn foo() -> Result<()> {
    if true {
        bail!(ErrorKind::FooError);
    } else {
        Ok(())
    }
}

fn bar() -> Result<()> {
    if true {
        bail!("bogus!");
    } else {
        Ok(())
    }
}

Chaining errors

error-chain supports extending an error chain by appending new errors. This can be done on a Result or on an existing Error.

To extend the error chain:

let res: Result<()> = do_something().chain_err(|| "something went wrong");

chain_err can be called on any Result type where the contained error type implements std::error::Error + Send + 'static, as long as the Result type's corresponding ResultExt trait is in scope. If the Result is an Err then chain_err evaluates the closure, which returns some type that can be converted to ErrorKind, boxes the original error to store as the cause, then returns a new error containing the original error.

Calling chain_err on an existing Error instance has the same signature and produces the same outcome as being called on a Result matching the properties described above. This is most useful when partially handling errors using the map_err function.

To chain an error directly, use with_chain:

let res: Result<()> =
    do_something().map_err(|e| Error::with_chain(e, "something went wrong"));

Linking errors

To convert an error from another error chain to this error chain:

error_chain! {
    links {
        OtherError(other::Error, other::ErrorKind);
    }
}

fn do_other_thing() -> other::Result<()> { unimplemented!() }

let res: Result<()> = do_other_thing().map_err(|e| e.into());

The Error and ErrorKind types implements From for the corresponding types of all linked error chains. Linked errors do not introduce a new cause to the error chain.

Matching errors

error-chain error variants are matched with simple patterns. Error is a tuple struct and its first field is the ErrorKind, making dispatching on error kinds relatively compact:

error_chain! {
    errors {
        InvalidToolchainName(t: String) {
            description("invalid toolchain name")
            display("invalid toolchain name: '{}'", t)
        }
    }
}

match Error::from("error!") {
    Error(ErrorKind::InvalidToolchainName(_), _) => { }
    Error(ErrorKind::Msg(_), _) => { }
}

Chained errors are also matched with (relatively) compact syntax

mod utils {
    error_chain! {
        errors {
            BadStuff {
                description("bad stuff")
            }
        }
    }
}

mod app {
    error_chain! {
        links {
            Utils(::utils::Error, ::utils::ErrorKind);
        }
    }
}


match app::Error::from("error!") {
    app::Error(app::ErrorKind::Utils(utils::ErrorKind::BadStuff), _) => { }
    _ => { }
}

Errors that do not conform to the same conventions as this library can still be included in the error chain. They are considered "foreign errors", and are declared using the foreign_links block of the error_chain! macro. Errors are automatically created from foreign errors by the try! macro.

Foreign links and regular links have one crucial difference: From conversions for regular links do not introduce a new error into the error chain, while conversions for foreign links always introduce a new error into the error chain. So for the example above all errors deriving from the std::fmt::Error type will be presented to the user as a new ErrorKind::Fmt variant, and the cause will be the original std::fmt::Error error. In contrast, when other_error::Error is converted to Error the two ErrorKinds are converted between each other to create a new Error but the old error is discarded; there is no "cause" created from the original error.

Backtraces

If the RUST_BACKTRACE environment variable is set to anything but 0, the earliest non-foreign error to be generated creates a single backtrace, which is passed through all From conversions and chain_err invocations of compatible types. To read the backtrace just call the backtrace() method.

Backtrace generation can be disabled by turning off the backtrace feature.

Iteration

The iter method returns an iterator over the chain of error boxes.

Modules

example_generated

These modules show an example of code generated by the macro. IT MUST NOT BE USED OUTSIDE THIS CRATE.

Macros

bail

Exits a function early with an error

ensure

Exits a function early with an error if the condition is not satisfied

error_chain

This macro is used for handling of duplicated and out-of-order fields. For the exact rules, see error_chain_processed.

error_chain_processed

Prefer to use error_chain instead of this macro.

quick_error
quick_main

Convenient wrapper to be able to use try! and such in the main. You can use it with a separated function:

Structs

Backtrace

Representation of an owned and self-contained backtrace.

Display

A struct which formats an error for output.

ErrorChainIter

Iterator over the error chain using the Error::cause() method.

Traits

ChainedError

This trait is implemented on all the errors generated by the error_chain macro.

ExitCode

Represents a value that can be used as the exit status of the process. See quick_main!.