• Stars
    star
    753
  • Rank 60,280 (Top 2 %)
  • Language
    Rust
  • License
    Other
  • Created over 4 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Custom hooks for colorful human oriented error reports via panics and the eyre crate

color-eyre

Build Status Latest Version Rust Documentation

An error report handler for panics and the eyre crate for colorful, consistent, and well formatted error reports for all kinds of errors.

TLDR

color_eyre helps you build error reports that look like this:

custom section example

Setup

Add the following to your toml file:

[dependencies]
color-eyre = "0.6"

And install the panic and error report handlers:

use color_eyre::eyre::Result;

fn main() -> Result<()> {
    color_eyre::install()?;

    // ...
    # Ok(())
}

Disabling tracing support

If you don't plan on using tracing_error and SpanTrace you can disable the tracing integration to cut down on unused dependencies:

[dependencies]
color-eyre = { version = "0.6", default-features = false }

Disabling SpanTrace capture by default

color-eyre defaults to capturing span traces. This is because SpanTrace capture is significantly cheaper than Backtrace capture. However, like backtraces, span traces are most useful for debugging applications, and it's not uncommon to want to disable span trace capture by default to keep noise out developer.

To disable span trace capture you must explicitly set one of the env variables that regulate SpanTrace capture to "0":

if std::env::var("RUST_SPANTRACE").is_err() {
    std::env::set_var("RUST_SPANTRACE", "0");
}

Improving perf on debug builds

In debug mode color-eyre behaves noticably worse than eyre. This is caused by the fact that eyre uses std::backtrace::Backtrace instead of backtrace::Backtrace. The std version of backtrace is precompiled with optimizations, this means that whether or not you're in debug mode doesn't matter much for how expensive backtrace capture is, it will always be in the 10s of milliseconds to capture. A debug version of backtrace::Backtrace however isn't so lucky, and can take an order of magnitude more time to capture a backtrace compared to its std counterpart.

Cargo profile overrides can be used to mitigate this problem. By configuring your project to always build backtrace with optimizations you should get the same performance from color-eyre that you're used to with eyre. To do so add the following to your Cargo.toml:

[profile.dev.package.backtrace]
opt-level = 3

Features

Multiple report format verbosity levels

color-eyre provides 3 different report formats for how it formats the captured SpanTrace and Backtrace, minimal, short, and full. Take the below snippets of the output produced by examples/usage.rs:


Running cargo run --example usage without RUST_LIB_BACKTRACE set will produce a minimal report like this:

minimal report format


Running RUST_LIB_BACKTRACE=1 cargo run --example usage tells color-eyre to use the short format, which additionally capture a backtrace::Backtrace:

short report format


Finally, running RUST_LIB_BACKTRACE=full cargo run --example usage tells color-eyre to use the full format, which in addition to the above will attempt to include source lines where the error originated from, assuming it can find them on the disk.

full report format

Custom Sections for error reports via Section trait

The section module provides helpers for adding extra sections to error reports. Sections are disinct from error messages and are displayed independently from the chain of errors. Take this example of adding sections to contain stderr and stdout from a failed command, taken from examples/custom_section.rs:

use color_eyre::{eyre::eyre, SectionExt, Section, eyre::Report};
use std::process::Command;
use tracing::instrument;

trait Output {
    fn output2(&mut self) -> Result<String, Report>;
}

impl Output for Command {
    #[instrument]
    fn output2(&mut self) -> Result<String, Report> {
        let output = self.output()?;

        let stdout = String::from_utf8_lossy(&output.stdout);

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            Err(eyre!("cmd exited with non-zero status code"))
                .with_section(move || stdout.trim().to_string().header("Stdout:"))
                .with_section(move || stderr.trim().to_string().header("Stderr:"))
        } else {
            Ok(stdout.into())
        }
    }
}

Here we have an function that, if the command exits unsuccessfully, creates a report indicating the failure and attaches two sections, one for stdout and one for stderr.

Running cargo run --example custom_section shows us how these sections are included in the output:

custom section example

Only the Stderr: section actually gets included. The cat command fails, so stdout ends up being empty and is skipped in the final report. This gives us a short and concise error report indicating exactly what was attempted and how it failed.

Aggregating multiple errors into one report

It's not uncommon for programs like batched task runners or parsers to want to return an error with multiple sources. The current version of the error trait does not support this use case very well, though there is work being done to improve this.

For now however one way to work around this is to compose errors outside the error trait. color-eyre supports such composition in its error reports via the Section trait.

For an example of how to aggregate errors check out examples/multiple_errors.rs.

Custom configuration for color-backtrace for setting custom filters and more

The pretty printing for backtraces and span traces isn't actually provided by color-eyre, but instead comes from its dependencies color-backtrace and color-spantrace. color-backtrace in particular has many more features than are exported by color-eyre, such as customized color schemes, panic hooks, and custom frame filters. The custom frame filters are particularly useful when combined with color-eyre, so to enable their usage we provide the install fn for setting up a custom BacktracePrinter with custom filters installed.

For an example of how to setup custom filters, check out examples/custom_filter.rs.

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

More Repositories

1

eyre

A trait object based error handling type for easy idiomatic error handling and reporting in Rust applications
Rust
886
star
2

displaydoc

A derive macro for implementing the display Trait via a doc comment and string interpolation
Rust
308
star
3

recaphub

CLI tool for generating a summary of recent github activity for people who are incredibly forgetful but still need to give weekly status updates to their boss without getting depressed and convincing themselves they did nothing because they can't remember what they did!
Rust
62
star
4

spandoc

Proc macro for using doc comments as context for errors/logs/profiling/whatever via `tracing`
Rust
44
star
5

uwubot

discord bot for uwuifying text
Rust
32
star
6

jane-eyre

A tracing aware eyre variant that captures SpanTraces and Backtraces and supports rich context for errors with warnings, suggestions, and notes
Rust
23
star
7

indenter

Display trait indentation helper for errors
Rust
22
star
8

laundry-bot

Program to process input from a vibration sensor and send discord messages when it thinks you've finished a load of laundry
Rust
19
star
9

color-anyhow

Rust
18
star
10

color-spantrace

pretty printer for `tracing_error::SpanTrace`
Rust
14
star
11

nostd-error-poc

Proof of Concept of a version of the error trait that is no-std compatible and works with backtraces / error return traces
Rust
10
star
12

stable-eyre

A custom context for eyre that supports backtraces on stable
Rust
10
star
13

sshish

A std::process::Command-like API for running commands via libssh2
Rust
9
star
14

trial-and-error

Experiment crate for proposals from the error handling project group
Rust
9
star
15

prs

My Work Tracker And Nonsense Repository, come say hi
Rust
7
star
16

gameoff

Our entry for https://itch.io/jam/game-off-2018
Rust
7
star
17

rustconf

JavaScript
6
star
18

btparse

A minimal deserialization library for std::backtrace::Backtrace's debug format
Rust
6
star
19

rust-template

Template for setting up maintainable rust crates
Rust
5
star
20

paige-and-jane-jams

My wife wants to get into game design and art so we're going to be doing mini game jams every couple of weeks to practice!
Rust
5
star
21

eyre-impl

An experimental crate on how to structure a maximally flexible catch all error type
Rust
4
star
22

adhocerr

Crate for the quick creation of anonymous error types from strings
Rust
4
star
23

error-return-traces

proof of concept for error return traces in rust
Rust
4
star
24

placeholder-game

Educational project on playdate game development
Batchfile
4
star
25

dotfiles

Jane Lusby's Configuration Files for well used applications.
Vim Script
4
star
26

errtools

itertools but for error handling
Rust
3
star
27

kvfmt

A helper macro for stringifying variables into a key=value style string
Rust
3
star
28

simple-eyre

A minimal error implementation ontop of eyre-impl
Rust
3
star
29

extracterr

Hacker Voice: I'm in (the error trait)
Rust
3
star
30

gcov-vim-parser

simple parser for gcov data that outputs in vim friendly formats
Rust
2
star
31

async-practice

Rust
2
star
32

yaahc.github.io

blog repo
Ruby
1
star
33

old-eyre

An experiment that is no longer in use
Rust
1
star
34

exploparse

example parser for poorly formed LC data
Rust
1
star
35

scdoall-rewrite

Example of a script I rewrote in rust
Rust
1
star
36

machine-learning

Git repo for machine learning projects
C++
1
star
37

algorithms

Git repository for Algorithms labs
C++
1
star
38

private-error-details

Example crate of hiding internal details of error types conveniently.
Rust
1
star