SkillAgentSearch skills...

Miette

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

Install / Use

/learn @zkat/Miette
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

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!):

<img src="https://raw.githubusercontent.com/zkat/miette/main/images/serde_json.png" alt="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&quot;:[&quot;json&quot;],&quot;title&quot;:&quot;&quot;,&quot;version&quot;:&quot;1.0.0&quot;},&quot;packageContent&quot;:&quot;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 <!-- omit in toc -->

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 [SourceCode]s 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, NamedSource, 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<String>,
    // 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::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();

    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:

<img src="https://raw.githubusercontent.com/zkat/miette/main/images/single-line-example.png" alt=" Narratable printout: \ diagnostic error code: oops::my::bad (link) Error: oops! \ Begin snippet for bad_file.rs starting at line 2, column 3 \ snippet line 1: source \ snippet line 2: text highlight starting at line 1, column 3: This bit here \ snippet line 3: here \ diagnostic help: try doing it better next time?">

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, SourceSpan};
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,

    #[error(transparent)]
    // Use `#[diagnostic(transparent)]` to wrap another [`Diagnostic`]. You won't see labels otherwise
    #[diagnostic(transparent)]
    AnotherError(#[from] AnotherError),

    /// Forward the diagnostic to a particular field.
    #[error("other error")]
    #[diagnostic(forward(the_actual_diagnostic))]
    EvenMoreData {
        unrelated_field_1: String,
        unrelated_field_2: usize,

        #[source]
        the_actual_diagnostic: AnotherError,
    }
}

#[derive(Error, Diagnostic, Debug)]
#[error("another error")]
pub struct AnotherError {
   #[label("here")]
   pub at: SourceSpan
}

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 [Diagnostic]s. 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> {
    "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> {
    "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, Result};
use semver::Version;

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

There are also similar [bail!] and [ensure!] macros.

... 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(())
}

Plea

View on GitHub
GitHub Stars2.5k
CategoryDevelopment
Updated6h ago
Forks150

Languages

Rust

Security Score

100/100

Audited on Mar 28, 2026

No findings