you run miette? You run her code like the software? Oh. Oh! Error code for coder! Error code for One Thousand Lines!
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!):
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.
std::error::Error
.anyhow
/eyre
-compatible error wrapper type, [Report],
which can be returned from main
.String
s included.The miette
crate also comes bundled with a default [ReportHandler] with the following features:
NO_COLOR
, and other heuristics.Using cargo-edit
:
sh
$ cargo add miette
If you want to use the fancy printer in all these screenshots:
sh
$ cargo add miette --features fancy
``rust
/*
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;
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. #[sourcecode] src: NamedSource, // Snippets and highlights can be included in the diagnostic! #[label("This bit here")] badbit: 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, NamedSource};
fn thisfails() -> 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".tostring();
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_reporter()
*/
fn pretendthisismain() -> Result<()> {
// kaboom~
thisfails()?;
Ok(())
} ```
And this is the output you'll get if you run this program:
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
.
```rust // lib/error.rs use thiserror::Error; use miette::Diagnostic;
pub enum MyLibError { #[error(transparent)] #[diagnostic(code(mylib::ioerror))] 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.
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::Error
s 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:
```rust // myapp/lib/myinternal_file.rs use miette::{IntoDiagnostic, Result}; use semver::Version;
pub fn sometool() -> Result
miette
also includes an anyhow
/eyre
-style Context
/WrapErr
traits that
you can import to add ad-hoc context messages to your Diagnostic
s, as well,
though you'll still need to use .into_diagnostic()
to make use of it:
```rust // myapp/lib/myinternal_file.rs use miette::{IntoDiagnostic, Result, WrapErr}; use semver::Version;
pub fn sometool() -> Result
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.
```rust use miette::{Result, IntoDiagnostic}; use semver::Version;
fn pretendthisismain() -> Result<()> { let version: Version = "1.2.x".parse().intodiagnostic()?; 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:
toml
miette = { version = "X.Y.Z", features = ["fancy"] }
miette
supports providing a URL for individual diagnostics. This URL will be
displayed as an actual link in supported terminals, like so:
To use this, you can add a url()
sub-param to your #[diagnostic]
attribute:
```rust use miette::Diagnostic; use thiserror::Error;
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:
```rust use miette::Diagnostic; use thiserror::Error;
code(my_app::my_error),
// Will link users to https://docs.rs/my_crate/0.0.0/my_crate/struct.MyErr.html
url(docsrs)
)]
struct MyErr; ```
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:
```rust use miette::{Diagnostic, SourceSpan}; use thiserror::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>!
} ```
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!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.