• Stars
    star
    2,005
  • Rank 23,098 (Top 0.5 %)
  • Language
    Rust
  • License
    Apache License 2.0
  • Created over 3 years ago
  • Updated about 2 months ago

Reviews

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

Repository Details

Fancy extension for std::error::Error with pretty, detailed diagnostic printing.

miette

You run miette? You run her code like the software? Oh. Oh! Error code for coder! Error code for One Thousand Lines!

About

miette is a diagnostic library for Rust. It includes a series of traits/protocols that allow you to hook into its error reporting facilities, and even write your own error reports! It lets you define error types that can print out like this (or in any format you like!):

Hi! miette also includes a screen-reader-oriented diagnostic printer that's enabled in various situations, such as when you use NO_COLOR or CLICOLOR settings, or on CI. This behavior is also fully configurable and customizable. For example, this is what this particular diagnostic will look like when the narrated printer is enabled:
\
Error: Received some bad JSON from the source. Unable to parse.
Caused by: missing field `foo` at line 1 column 1700
\
Begin snippet for https://api.nuget.org/v3/registration5-gz-semver2/json.net/index.json starting
at line 1, column 1659
\
snippet line 1: gs":["json"],"title":"","version":"1.0.0"},"packageContent":"https://api.nuget.o
highlight starting at line 1, column 1699: last parsing location
\
diagnostic help: This is a bug. It might be in ruget, or it might be in the
source you're using, but it's definitely a bug and should be reported.
diagnostic error code: ruget::api::bad_json

NOTE: You must enable the "fancy" crate feature to get fancy report output like in the screenshots above. You should only do this in your toplevel crate, as the fancy feature pulls in a number of dependencies that libraries and such might not want.

Table of Contents

Features

  • Generic Diagnostic protocol, compatible (and dependent on) std::error::Error.
  • Unique error codes on every Diagnostic.
  • Custom links to get more details on error codes.
  • Super handy derive macro for defining diagnostic metadata.
  • Replacements for anyhow/eyre types Result, Report and the miette! macro for the anyhow!/eyre! macros.
  • Generic support for arbitrary SourceCodes for snippet data, with default support for Strings included.

The miette crate also comes bundled with a default ReportHandler with the following features:

  • Fancy graphical diagnostic output, using ANSI/Unicode text
  • single- and multi-line highlighting support
  • Screen reader/braille support, gated on NO_COLOR, and other heuristics.
  • Fully customizable graphical theming (or overriding the printers entirely).
  • Cause chain printing
  • Turns diagnostic codes into links in supported terminals.

Installing

$ cargo add miette

If you want to use the fancy printer in all these screenshots:

$ cargo add miette --features fancy

Example

/*
You can derive a `Diagnostic` from any `std::error::Error` type.

`thiserror` is a great way to define them, and plays nicely with `miette`!
*/
use miette::{Diagnostic, SourceSpan};
use thiserror::Error;

#[derive(Error, Debug, Diagnostic)]
#[error("oops!")]
#[diagnostic(
    code(oops::my::bad),
    url(docsrs),
    help("try doing it better next time?")
)]
struct MyBad {
    // The Source that we're gonna be printing snippets out of.
    // This can be a String if you don't have or care about file names.
    #[source_code]
    src: NamedSource,
    // Snippets and highlights can be included in the diagnostic!
    #[label("This bit here")]
    bad_bit: SourceSpan,
}

/*
Now let's define a function!

Use this `Result` type (or its expanded version) as the return type
throughout your app (but NOT your libraries! Those should always return
concrete types!).
*/
use miette::{NamedSource, Result};
fn this_fails() -> Result<()> {
    // You can use plain strings as a `Source`, or anything that implements
    // the one-method `Source` trait.
    let src = "source\n  text\n    here".to_string();
    let len = src.len();

    Err(MyBad {
        src: NamedSource::new("bad_file.rs", src),
        bad_bit: (9, 4).into(),
    })?;

    Ok(())
}

/*
Now to get everything printed nicely, just return a `Result<()>`
and you're all set!

Note: You can swap out the default reporter for a custom one using
`miette::set_hook()`
*/
fn pretend_this_is_main() -> Result<()> {
    // kaboom~
    this_fails()?;

    Ok(())
}

And this is the output you'll get if you run this program:


Narratable printout:
\
Error: Types mismatched for operation.
Diagnostic severity: error
Begin snippet starting at line 1, column 1
\
snippet line 1: 3 + "5"
label starting at line 1, column 1: int
label starting at line 1, column 1: doesn't support these values.
label starting at line 1, column 1: string
diagnostic help: Change int or string to be the right types and try again.
diagnostic code: nu::parser::unsupported_operation
For more details, see https://docs.rs/nu-parser/0.1.0/nu-parser/enum.ParseError.html#variant.UnsupportedOperation

Using

... in libraries

miette is fully compatible with library usage. Consumers who don't know about, or don't want, miette features can safely use its error types as regular std::error::Error.

We highly recommend using something like thiserror to define unique error types and error wrappers for your library.

While miette integrates smoothly with thiserror, it is not required. If you don't want to use the Diagnostic derive macro, you can implement the trait directly, just like with std::error::Error.

// lib/error.rs
use miette::Diagnostic;
use thiserror::Error;

#[derive(Error, Diagnostic, Debug)]
pub enum MyLibError {
    #[error(transparent)]
    #[diagnostic(code(my_lib::io_error))]
    IoError(#[from] std::io::Error),

    #[error("Oops it blew up")]
    #[diagnostic(code(my_lib::bad_code))]
    BadThingHappened,
}

Then, return this error type from all your fallible public APIs. It's a best practice to wrap any "external" error types in your error enum instead of using something like Report in a library.

... in application code

Application code tends to work a little differently than libraries. You don't always need or care to define dedicated error wrappers for errors coming from external libraries and tools.

For this situation, miette includes two tools: Report and IntoDiagnostic. They work in tandem to make it easy to convert regular std::error::Errors into Diagnostics. Additionally, there's a Result type alias that you can use to be more terse.

When dealing with non-Diagnostic types, you'll want to .into_diagnostic() them:

// my_app/lib/my_internal_file.rs
use miette::{IntoDiagnostic, Result};
use semver::Version;

pub fn some_tool() -> Result<Version> {
    Ok("1.2.x".parse().into_diagnostic()?)
}

miette also includes an anyhow/eyre-style Context/WrapErr traits that you can import to add ad-hoc context messages to your Diagnostics, as well, though you'll still need to use .into_diagnostic() to make use of it:

// my_app/lib/my_internal_file.rs
use miette::{IntoDiagnostic, Result, WrapErr};
use semver::Version;

pub fn some_tool() -> Result<Version> {
    Ok("1.2.x"
        .parse()
        .into_diagnostic()
        .wrap_err("Parsing this tool's semver version failed.")?)
}

To construct your own simple adhoc error use the miette! macro:

// my_app/lib/my_internal_file.rs
use miette::{miette, IntoDiagnostic, Result, WrapErr};
use semver::Version;

pub fn some_tool() -> Result<Version> {
    let version = "1.2.x";
    Ok(version
        .parse()
        .map_err(|_| miette!("Invalid version {}", version))?)
}

... in main()

main() is just like any other part of your application-internal code. Use Result as your return value, and it will pretty-print your diagnostics automatically.

NOTE: You must enable the "fancy" crate feature to get fancy report output like in the screenshots here.** You should only do this in your toplevel crate, as the fancy feature pulls in a number of dependencies that libraries and such might not want.

use miette::{IntoDiagnostic, Result};
use semver::Version;

fn pretend_this_is_main() -> Result<()> {
    let version: Version = "1.2.x".parse().into_diagnostic()?;
    println!("{}", version);
    Ok(())
}

Please note: in order to get fancy diagnostic rendering with all the pretty colors and arrows, you should install miette with the fancy feature enabled:

miette = { version = "X.Y.Z", features = ["fancy"] }

... diagnostic code URLs

miette supports providing a URL for individual diagnostics. This URL will be displayed as an actual link in supported terminals, like so:

 Example showing the graphical report printer for miette
pretty-printing an error code. The code is underlined and followed by text
saying to 'click here'. A hover tooltip shows a full-fledged URL that can be
Ctrl+Clicked to open in a browser.
\
This feature is also available in the narratable printer. It will add a line
after printing the error code showing a plain URL that you can visit.

To use this, you can add a url() sub-param to your #[diagnostic] attribute:

use miette::Diagnostic;
use thiserror::Error;

#[derive(Error, Diagnostic, Debug)]
#[error("kaboom")]
#[diagnostic(
    code(my_app::my_error),
    // You can do formatting!
    url("https://my_website.com/error_codes#{}", self.code().unwrap())
)]
struct MyErr;

Additionally, if you're developing a library and your error type is exported from your crate's top level, you can use a special url(docsrs) option instead of manually constructing the URL. This will automatically create a link to this diagnostic on docs.rs, so folks can just go straight to your (very high quality and detailed!) documentation on this diagnostic:

use miette::Diagnostic;
use thiserror::Error;

#[derive(Error, Diagnostic, Debug)]
#[diagnostic(
    code(my_app::my_error),
    // Will link users to https://docs.rs/my_crate/0.0.0/my_crate/struct.MyErr.html
    url(docsrs)
)]
#[error("kaboom")]
struct MyErr;

... snippets

Along with its general error handling and reporting features, miette also includes facilities for adding error spans/annotations/labels to your output. This can be very useful when an error is syntax-related, but you can even use it to print out sections of your own source code!

To achieve this, miette defines its own lightweight SourceSpan type. This is a basic byte-offset and length into an associated SourceCode and, along with the latter, gives miette all the information it needs to pretty-print some snippets! You can also use your own Into<SourceSpan> types as label spans.

The easiest way to define errors like this is to use the derive(Diagnostic) macro:

use miette::{Diagnostic, SourceSpan};
use thiserror::Error;

#[derive(Diagnostic, Debug, Error)]
#[error("oops")]
#[diagnostic(code(my_lib::random_error))]
pub struct MyErrorType {
    // The `Source` that miette will use.
    #[source_code]
    src: String,

    // This will underline/mark the specific code inside the larger
    // snippet context.
    #[label = "This is the highlight"]
    err_span: SourceSpan,

    // You can add as many labels as you want.
    // They'll be rendered sequentially.
    #[label("This is bad")]
    snip2: (usize, usize), // `(usize, usize)` is `Into<SourceSpan>`!

    // Snippets can be optional, by using Option:
    #[label("some text")]
    snip3: Option<SourceSpan>,

    // with or without label text
    #[label]
    snip4: Option<SourceSpan>,
}

... help text

miette provides two facilities for supplying help text for your errors:

The first is the #[help()] format attribute that applies to structs or enum variants:

use miette::Diagnostic;
use thiserror::Error;

#[derive(Debug, Diagnostic, Error)]
#[error("welp")]
#[diagnostic(help("try doing this instead"))]
struct Foo;

The other is by programmatically supplying the help text as a field to your diagnostic:

use miette::Diagnostic;
use thiserror::Error;

#[derive(Debug, Diagnostic, Error)]
#[error("welp")]
#[diagnostic()]
struct Foo {
    #[help]
    advice: Option<String>, // Can also just be `String`
}

let err = Foo {
    advice: Some("try doing this instead".to_string()),
};

... multiple related errors

miette supports collecting multiple errors into a single diagnostic, and printing them all together nicely.

To do so, use the #[related] tag on any IntoIter field in your Diagnostic type:

use miette::Diagnostic;
use thiserror::Error;

#[derive(Debug, Error, Diagnostic)]
#[error("oops")]
struct MyError {
    #[related]
    others: Vec<MyError>,
}

... delayed source code

Sometimes it makes sense to add source code to the error message later. One option is to use with_source_code() method for that:

use miette::{Diagnostic, SourceSpan};
use thiserror::Error;

#[derive(Diagnostic, Debug, Error)]
#[error("oops")]
#[diagnostic()]
pub struct MyErrorType {
    // Note: label but no source code
    #[label]
    err_span: SourceSpan,
}

fn do_something() -> miette::Result<()> {
    // This function emits actual error with label
    return Err(MyErrorType {
        err_span: (7..11).into(),
    })?;
}

fn main() -> miette::Result<()> {
    do_something().map_err(|error| {
        // And this code provides the source code for inner error
        error.with_source_code(String::from("source code"))
    })
}

Also source code can be provided by a wrapper type. This is especially useful in combination with related, when multiple errors should be emitted at the same time:

use miette::{Diagnostic, Report, SourceSpan};
use thiserror::Error;

#[derive(Diagnostic, Debug, Error)]
#[error("oops")]
#[diagnostic()]
pub struct InnerError {
    // Note: label but no source code
    #[label]
    err_span: SourceSpan,
}

#[derive(Diagnostic, Debug, Error)]
#[error("oops: multiple errors")]
#[diagnostic()]
pub struct MultiError {
    // Note source code by no labels
    #[source_code]
    source_code: String,
    // The source code above is used for these errors
    #[related]
    related: Vec<InnerError>,
}

fn do_something() -> Result<(), Vec<InnerError>> {
    Err(vec![
        InnerError {
            err_span: (0..6).into(),
        },
        InnerError {
            err_span: (7..11).into(),
        },
    ])
}

fn main() -> miette::Result<()> {
    do_something().map_err(|err_list| MultiError {
        source_code: "source code".into(),
        related: err_list,
    })?;
    Ok(())
}

... Diagnostic-based error sources.

When one uses the #[source] attribute on a field, that usually comes from thiserror, and implements a method for [std::error::Error::source]. This works in many cases, but it's lossy: if the source of the diagnostic is a diagnostic itself, the source will simply be treated as an std::error::Error.

While this has no effect on the existing reporters, since they don't use that information right now, APIs who might want this information will have no access to it.

If it's important for you for this information to be available to users, you can use #[diagnostic_source] alongside #[source]. Not that you will likely want to use both:

use miette::Diagnostic;
use thiserror::Error;

#[derive(Debug, Diagnostic, Error)]
#[error("MyError")]
struct MyError {
    #[source]
    #[diagnostic_source]
    the_cause: OtherError,
}

#[derive(Debug, Diagnostic, Error)]
#[error("OtherError")]
struct OtherError;

... handler options

MietteHandler is the default handler, and is very customizable. In most cases, you can simply use MietteHandlerOpts to tweak its behavior instead of falling back to your own custom handler.

Usage is like so:

miette::set_hook(Box::new(|_| {
    Box::new(
        miette::MietteHandlerOpts::new()
            .terminal_links(true)
            .unicode(false)
            .context_lines(3)
            .tab_width(4)
            .build(),
    )
}))

See the docs for MietteHandlerOpts for more details on what you can customize!

... dynamic diagnostics

If you...

  • ...don't know all the possible errors upfront
  • ...need to serialize/deserialize errors then you may want to use miette!, diagnostic! macros or MietteDiagnostic directly to create diagnostic on the fly.
let source = "2 + 2 * 2 = 8".to_string();
let report = miette!(
  labels = vec[
      LabeledSpan::at(12..13, "this should be 6"),
  ],
  help = "'*' has greater precedence than '+'",
  "Wrong answer"
).with_source_code(source);
println!("{:?}", report)

Acknowledgements

miette was not developed in a void. It owes enormous credit to various other projects and their authors:

  • anyhow and color-eyre: these two enormously influential error handling libraries have pushed forward the experience of application-level error handling and error reporting. miette's Report type is an attempt at a very very rough version of their Report types.
  • thiserror for setting the standard for library-level error definitions, and for being the inspiration behind miette's derive macro.
  • rustc and @estebank for their state-of-the-art work in compiler diagnostics.
  • ariadne for pushing forward how pretty these diagnostics can really look!

License

miette is released to the Rust community under the Apache license 2.0.

It also includes code taken from eyre, and some from thiserror, also under the Apache License. Some code is taken from ariadne, which is MIT licensed.

More Repositories

1

npx

execute npm package binaries (moved)
JavaScript
2,625
star
2

big-brain

Utility AI library for the Bevy game engine
Rust
1,032
star
3

cacache-rs

A high-performance, concurrent, content-addressable disk cache, with support for both sync and async APIs. 💩💵 but for your 🦀
Rust
529
star
4

cipm

standalone ci-oriented package installer for npm projects (moved)
JavaScript
400
star
5

make-fetch-happen

Get in loser, we're making requests!
JavaScript
384
star
6

pacote

programmatic npm package and metadata downloader (moved!)
JavaScript
280
star
7

cacache

💩💵 but for your data. If you've got the hash, we've got the cache ™ (moved)
JavaScript
240
star
8

chanl

Portable channel-based concurrency for Common Lisp
Common Lisp
164
star
9

mona

Composable parsing for JavaScript
JavaScript
152
star
10

rust-notes

Personal notes while learning Rust. Mainly documenting pain points along the way.
145
star
11

maybe-hugs

Polyglot implementations of conditional hugging
OCaml
114
star
12

proposal-as-patterns

`as` destructuring patterns
105
star
13

sheeple

Cheeky prototypes for Common Lisp
Common Lisp
99
star
14

pattycake

playground for pattern matching api
JavaScript
98
star
15

ssri

Standard Subresource Integrity library for Node.js
JavaScript
82
star
16

json-parse-better-errors

get better errors
JavaScript
67
star
17

squirl

Common Lisp port of the Chipmunk 2d physics library
Common Lisp
53
star
18

supports-color

Detects whether a terminal supports color, and gives details about that support
Rust
42
star
19

figgy-pudding

Cascading, controlled-visibility options object management.
JavaScript
39
star
20

genfun

Prototype-friendly multimethods for JavaScript.
JavaScript
38
star
21

ssri-rs

Rusty implementation of Subresource Integrity
Rust
38
star
22

can.viewify

require() mustache and ejs modules as compiled CanJS views
JavaScript
37
star
23

protoduck

Duck typing for the most serious of ducks.
JavaScript
35
star
24

chillax

CouchDB abstraction layer for Common Lisp
Common Lisp
34
star
25

cl-openal

Common Lisp bindings for the OpenAL audio library.
Common Lisp
34
star
26

conserv

Common Lisp
31
star
27

memento-mori

Robustness through actors, for Common Lisp
Common Lisp
31
star
28

talks

Notes and slides for all my talks
JavaScript
26
star
29

until-it-dies

A batteries-included game engine.
Common Lisp
25
star
30

supports-hyperlinks

Detect whether the current terminal supports rendering hyperlinks
Rust
25
star
31

matrix-curious

FAQ and resources for those curious about joining the Matrix network!
23
star
32

sykobot

An IRC bot from another universe. No, really.
Common Lisp
21
star
33

turron

Rusty NuGet client
Rust
20
star
34

npm-pick-manifest

Standard manifest picker/semver resolver for npm
JavaScript
20
star
35

cl-ffmpeg

CFFI bindings for FFMPEG
Common Lisp
19
star
36

proposal-collection-literals

[WITHDRAWN] tc39 proposal for custom collection literals
18
star
37

cl-devil

Common Lisp bindings for DevIL
Common Lisp
16
star
38

okimdone

tells you when it's done
Shell
15
star
39

srisum-rs

Compute and check subresource integrity digests.
Rust
14
star
40

thisdiagnostic

Add nice user-facing diagnostics to your errors without being weird about it.
Rust
14
star
41

is_ci

Super lightweight and dead-simple CI detection.
Rust
12
star
42

common-worm

A simple, hackish version of the classic snake game, written in Common Lisp
Common Lisp
12
star
43

supports-unicode

Detects whether a terminal supports unicode.
Rust
12
star
44

nanotubes

Fancy websocket wrapper for Rust
Rust
12
star
45

srisum

Compute and check Subresource Integrity digests.
JavaScript
11
star
46

DWG.Directories

Standard directories for .NET
10
star
47

cadr

content-addressable filesystem snapshots
JavaScript
10
star
48

protocols

Multi-type protocol-based polymorphism
JavaScript
10
star
49

cl-speedy-queue

Lightweight, optimized queue implementation for CL
Common Lisp
9
star
50

playwright

Like Erlang, but not
JavaScript
9
star
51

sykosomatic

Cooperative storytelling
Common Lisp
7
star
52

cond

Restartable error handling system for JavaScript
JavaScript
7
star
53

destealify

Browserify transform for processing StealJS modules
JavaScript
7
star
54

bacon-browser

Utility library for higher-level, declarative interaction with various bits of browser-level events and features.
JavaScript
7
star
55

sykosomatic-legacy

text-based online game engine
Common Lisp
7
star
56

shepherdb

A Sheeple-based persistent object store.
Common Lisp
6
star
57

clutter

nothing to see here
Common Lisp
6
star
58

facile

CouchDB view server for Factor
Factor
6
star
59

fl-protocols

fantasy-land specification bridge for @zkat/protocols
JavaScript
6
star
60

electron-collider

Rust
5
star
61

my-precious

a local package archive, of our own
JavaScript
5
star
62

checksum-stream

Calculates and/or checks data coming through a stream and emits the digest before stream end.
JavaScript
5
star
63

cl-form

Generic form validation utility for CL
Common Lisp
5
star
64

common-brick

Breakout clone with "realistic" physics.
Common Lisp
4
star
65

surf-middleware-cache

http caching middleware for the Surf http client
Rust
4
star
66

specificity

Runnable specifications for Common Lisp
4
star
67

friendfavor

Find out what your friends think of something -- or someone!
Common Lisp
4
star
68

shortening

The personal URL shortener.
Common Lisp
3
star
69

kallisti

kallisti
Rust
3
star
70

clutterscript

Pay this no heed, I'm just learning stuff.
JavaScript
3
star
71

cl-event2

libevent2 bindings for Common Lisp
Common Lisp
3
star
72

yashmup

Toy project -- writing a shmup in CL
Common Lisp
3
star
73

test

just a place to test random github shit
2
star
74

marina

placeholder for programming language
2
star
75

mona-csv

simple mona-based csv parser
JavaScript
1
star
76

proto

Alternative to JavaScript's `new`.
Makefile
1
star
77

dynvar

Dynamic variables for JS
JavaScript
1
star
78

protoduck-fl

fantasy-land specification bridge for protoduck
JavaScript
1
star
79

mona-json

mona-based JSON parser
JavaScript
1
star
80

mona-strings

String parsers for mona
JavaScript
1
star
81

logloc

Adds source location to console loggers
JavaScript
1
star
82

zkat

it me
1
star
83

node-otp

The Node.js Open Telecom Platform
1
star
84

fetch-cache

Cache API implementation + protocol
JavaScript
1
star
85

tswrp

JavaScript
1
star
86

chownr-rs

Like chown -r for Rust
Rust
1
star
87

presentations

various presentations
JavaScript
1
star
88

storychat

~~~ tell me a story <3 with your words ~~~
JavaScript
1
star
89

mona-combinators

Parser combinators for mona
JavaScript
1
star
90

fig-roll

rolls up your configs into a nice figgy pudding
1
star
91

chatoid

Toy chatroom using webrtc
JavaScript
1
star
92

ironsworn-mechanics

Various support utilities and some custom rendering for mechanics in Ironsworn-family games (Starforged, Sundered Isles, etc).
TypeScript
1
star
93

zkat.github.io

Web sight
TypeScript
1
star