一个用于 std::error::Error 的漂亮、详细的诊断打印的扩展。
mietteYou 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 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.
Diagnostic] protocol, compatible (and dependent on)
[std::error::Error].Diagnostic].anyhow/eyre
types [Result], [Report] and the [miette!] macro for the
anyhow!/eyre! macros.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:
NO_COLOR,
and other heuristics.$ cargo add miette
If you want to use the fancy printer in all these screenshots:
$ cargo add miette --features fancy
…
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.
…
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::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.
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"] }
Another way to display a diagnostic is by printing them using the debug formatter. This is, in fact, what returning diagnostics from main ends up doing. To do it yourself, you can write the following:
use miette::{IntoDiagnostic, Result};
use semver::Version;
fn just_a_random_function() {
let version_result: Result<Version> = "1.2.x".parse().into_diagnostic();
match version_result {
Err(e) => println!("{:?}", e),
Ok(version) => println!("{}", version),
}
}
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:
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;
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:
…
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()),
};
miette provides a way to set the severity level of a diagnostic.
use miette::Diagnostic;
use thiserror::Error;
#[derive(Debug, Diagnostic, Error)]
#[error("welp")]
#[diagnostic(severity(Warning))]
struct Foo;
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>,
}
Sometimes it makes sense to add source code to the error message later.
One option is to use with_source_code()
method for that:
…
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:
…
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;
[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)
.break_words(true)
.build(),
)
}))
See the docs for [MietteHandlerOpts] for more details on what you can
customize!
If you...
暂无开放 Issues,或尚未同步最近议题。