README.md
1
2# `miette`
3
4You run miette? You run her code like the software? Oh. Oh! Error code for
5coder! Error code for One Thousand Lines!
6
7### About
8
9`miette` is a diagnostic library for Rust. It includes a series of
10traits/protocols that allow you to hook into its error reporting facilities,
11and even write your own error reports! It lets you define error types that
12can print out like this (or in any format you like!):
13
14<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:
15\
16Error: Received some bad JSON from the source. Unable to parse.
17 Caused by: missing field `foo` at line 1 column 1700
18\
19Begin snippet for https://api.nuget.org/v3/registration5-gz-semver2/json.net/index.json starting
20at line 1, column 1659
21\
22snippet line 1: gs":["json"],"title":"","version":"1.0.0"},"packageContent":"https://api.nuget.o
23 highlight starting at line 1, column 1699: last parsing location
24\
25diagnostic help: This is a bug. It might be in ruget, or it might be in the
26source you're using, but it's definitely a bug and should be reported.
27diagnostic error code: ruget::api::bad_json
28" />
29
30> **NOTE: You must enable the `"fancy"` crate feature to get fancy report
31output like in the screenshots above.** You should only do this in your
32toplevel crate, as the fancy feature pulls in a number of dependencies that
33libraries and such might not want.
34
35### Table of Contents <!-- omit in toc -->
36
37- [About](#about)
38- [Features](#features)
39- [Installing](#installing)
40- [Example](#example)
41- [Using](#using)
42 - [... in libraries](#-in-libraries)
43 - [... in application code](#-in-application-code)
44 - [... in `main()`](#-in-main)
45 - [... diagnostic code URLs](#-diagnostic-code-urls)
46 - [... snippets](#-snippets)
47 - [... multiple related errors](#-multiple-related-errors)
48 - [... delayed source code](#-delayed-source-code)
49 - [... handler options](#-handler-options)
50 - [... dynamic diagnostics](#-dynamic-diagnostics)
51- [Acknowledgements](#acknowledgements)
52- [License](#license)
53
54### Features
55
56- Generic [`Diagnostic`] protocol, compatible (and dependent on)
57 [`std::error::Error`].
58- Unique error codes on every [`Diagnostic`].
59- Custom links to get more details on error codes.
60- Super handy derive macro for defining diagnostic metadata.
61- Replacements for [`anyhow`](https://docs.rs/anyhow)/[`eyre`](https://docs.rs/eyre)
62 types [`Result`], [`Report`] and the [`miette!`] macro for the
63 `anyhow!`/`eyre!` macros.
64- Generic support for arbitrary [`SourceCode`]s for snippet data, with
65 default support for `String`s included.
66
67The `miette` crate also comes bundled with a default [`ReportHandler`] with
68the following features:
69
70- Fancy graphical [diagnostic output](#about), using ANSI/Unicode text
71- single- and multi-line highlighting support
72- Screen reader/braille support, gated on [`NO_COLOR`](http://no-color.org/),
73 and other heuristics.
74- Fully customizable graphical theming (or overriding the printers
75 entirely).
76- Cause chain printing
77- Turns diagnostic codes into links in [supported terminals](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda).
78
79### Installing
80
81```sh
82$ cargo add miette
83```
84
85If you want to use the fancy printer in all these screenshots:
86
87```sh
88$ cargo add miette --features fancy
89```
90
91### Example
92
93```rust
94/*
95You can derive a `Diagnostic` from any `std::error::Error` type.
96
97`thiserror` is a great way to define them, and plays nicely with `miette`!
98*/
99use miette::{Diagnostic, SourceSpan};
100use thiserror::Error;
101
102#[derive(Error, Debug, Diagnostic)]
103#[error("oops!")]
104#[diagnostic(
105 code(oops::my::bad),
106 url(docsrs),
107 help("try doing it better next time?")
108)]
109struct MyBad {
110 // The Source that we're gonna be printing snippets out of.
111 // This can be a String if you don't have or care about file names.
112 #[source_code]
113 src: NamedSource,
114 // Snippets and highlights can be included in the diagnostic!
115 #[label("This bit here")]
116 bad_bit: SourceSpan,
117}
118
119/*
120Now let's define a function!
121
122Use this `Result` type (or its expanded version) as the return type
123throughout your app (but NOT your libraries! Those should always return
124concrete types!).
125*/
126use miette::{NamedSource, Result};
127fn this_fails() -> Result<()> {
128 // You can use plain strings as a `Source`, or anything that implements
129 // the one-method `Source` trait.
130 let src = "source\n text\n here".to_string();
131 let len = src.len();
132
133 Err(MyBad {
134 src: NamedSource::new("bad_file.rs", src),
135 bad_bit: (9, 4).into(),
136 })?;
137
138 Ok(())
139}
140
141/*
142Now to get everything printed nicely, just return a `Result<()>`
143and you're all set!
144
145Note: You can swap out the default reporter for a custom one using
146`miette::set_hook()`
147*/
148fn pretend_this_is_main() -> Result<()> {
149 // kaboom~
150 this_fails()?;
151
152 Ok(())
153}
154```
155
156And this is the output you'll get if you run this program:
157
158<img src="https://raw.githubusercontent.com/zkat/miette/main/images/single-line-example.png" alt="
159Narratable printout:
160\
161Error: Types mismatched for operation.
162 Diagnostic severity: error
163Begin snippet starting at line 1, column 1
164\
165snippet line 1: 3 + "5"
166 label starting at line 1, column 1: int
167 label starting at line 1, column 1: doesn't support these values.
168 label starting at line 1, column 1: string
169diagnostic help: Change int or string to be the right types and try again.
170diagnostic code: nu::parser::unsupported_operation
171For more details, see https://docs.rs/nu-parser/0.1.0/nu-parser/enum.ParseError.html#variant.UnsupportedOperation">
172
173### Using
174
175#### ... in libraries
176
177`miette` is _fully compatible_ with library usage. Consumers who don't know
178about, or don't want, `miette` features can safely use its error types as
179regular [`std::error::Error`].
180
181We highly recommend using something like [`thiserror`](https://docs.rs/thiserror)
182to define unique error types and error wrappers for your library.
183
184While `miette` integrates smoothly with `thiserror`, it is _not required_.
185If you don't want to use the [`Diagnostic`] derive macro, you can implement
186the trait directly, just like with `std::error::Error`.
187
188```rust
189// lib/error.rs
190use miette::{Diagnostic, SourceSpan};
191use thiserror::Error;
192
193#[derive(Error, Diagnostic, Debug)]
194pub enum MyLibError {
195 #[error(transparent)]
196 #[diagnostic(code(my_lib::io_error))]
197 IoError(#[from] std::io::Error),
198
199 #[error("Oops it blew up")]
200 #[diagnostic(code(my_lib::bad_code))]
201 BadThingHappened,
202
203 #[error(transparent)]
204 // Use `#[diagnostic(transparent)]` to wrap another [`Diagnostic`]. You won't see labels otherwise
205 #[diagnostic(transparent)]
206 AnotherError(#[from] AnotherError),
207}
208
209#[derive(Error, Diagnostic, Debug)]
210#[error("another error")]
211pub struct AnotherError {
212 #[label("here")]
213 pub at: SourceSpan
214}
215```
216
217Then, return this error type from all your fallible public APIs. It's a best
218practice to wrap any "external" error types in your error `enum` instead of
219using something like [`Report`] in a library.
220
221#### ... in application code
222
223Application code tends to work a little differently than libraries. You
224don't always need or care to define dedicated error wrappers for errors
225coming from external libraries and tools.
226
227For this situation, `miette` includes two tools: [`Report`] and
228[`IntoDiagnostic`]. They work in tandem to make it easy to convert regular
229`std::error::Error`s into [`Diagnostic`]s. Additionally, there's a
230[`Result`] type alias that you can use to be more terse.
231
232When dealing with non-`Diagnostic` types, you'll want to
233`.into_diagnostic()` them:
234
235```rust
236// my_app/lib/my_internal_file.rs
237use miette::{IntoDiagnostic, Result};
238use semver::Version;
239
240pub fn some_tool() -> Result<Version> {
241 Ok("1.2.x".parse().into_diagnostic()?)
242}
243```
244
245`miette` also includes an `anyhow`/`eyre`-style `Context`/`WrapErr` traits
246that you can import to add ad-hoc context messages to your `Diagnostic`s, as
247well, though you'll still need to use `.into_diagnostic()` to make use of
248it:
249
250```rust
251// my_app/lib/my_internal_file.rs
252use miette::{IntoDiagnostic, Result, WrapErr};
253use semver::Version;
254
255pub fn some_tool() -> Result<Version> {
256 Ok("1.2.x"
257 .parse()
258 .into_diagnostic()
259 .wrap_err("Parsing this tool's semver version failed.")?)
260}
261```
262
263To construct your own simple adhoc error use the [miette!] macro:
264```rust
265// my_app/lib/my_internal_file.rs
266use miette::{miette, IntoDiagnostic, Result, WrapErr};
267use semver::Version;
268
269pub fn some_tool() -> Result<Version> {
270 let version = "1.2.x";
271 Ok(version
272 .parse()
273 .map_err(|_| miette!("Invalid version {}", version))?)
274}
275```
276There are also similar [bail!] and [ensure!] macros.
277
278#### ... in `main()`
279
280`main()` is just like any other part of your application-internal code. Use
281`Result` as your return value, and it will pretty-print your diagnostics
282automatically.
283
284> **NOTE:** You must enable the `"fancy"` crate feature to get fancy report
285output like in the screenshots here.** You should only do this in your
286toplevel crate, as the fancy feature pulls in a number of dependencies that
287libraries and such might not want.
288
289```rust
290use miette::{IntoDiagnostic, Result};
291use semver::Version;
292
293fn pretend_this_is_main() -> Result<()> {
294 let version: Version = "1.2.x".parse().into_diagnostic()?;
295 println!("{}", version);
296 Ok(())
297}
298```
299
300Please note: in order to get fancy diagnostic rendering with all the pretty
301colors and arrows, you should install `miette` with the `fancy` feature
302enabled:
303
304```toml
305miette = { version = "X.Y.Z", features = ["fancy"] }
306```
307
308#### ... diagnostic code URLs
309
310`miette` supports providing a URL for individual diagnostics. This URL will
311be displayed as an actual link in supported terminals, like so:
312
313<img
314src="https://raw.githubusercontent.com/zkat/miette/main/images/code_linking.png"
315alt=" Example showing the graphical report printer for miette
316pretty-printing an error code. The code is underlined and followed by text
317saying to 'click here'. A hover tooltip shows a full-fledged URL that can be
318Ctrl+Clicked to open in a browser.
319\
320This feature is also available in the narratable printer. It will add a line
321after printing the error code showing a plain URL that you can visit.
322">
323
324To use this, you can add a `url()` sub-param to your `#[diagnostic]`
325attribute:
326
327```rust
328use miette::Diagnostic;
329use thiserror::Error;
330
331#[derive(Error, Diagnostic, Debug)]
332#[error("kaboom")]
333#[diagnostic(
334 code(my_app::my_error),
335 // You can do formatting!
336 url("https://my_website.com/error_codes#{}", self.code().unwrap())
337)]
338struct MyErr;
339```
340
341Additionally, if you're developing a library and your error type is exported
342from your crate's top level, you can use a special `url(docsrs)` option
343instead of manually constructing the URL. This will automatically create a
344link to this diagnostic on `docs.rs`, so folks can just go straight to your
345(very high quality and detailed!) documentation on this diagnostic:
346
347```rust
348use miette::Diagnostic;
349use thiserror::Error;
350
351#[derive(Error, Diagnostic, Debug)]
352#[diagnostic(
353 code(my_app::my_error),
354 // Will link users to https://docs.rs/my_crate/0.0.0/my_crate/struct.MyErr.html
355 url(docsrs)
356)]
357#[error("kaboom")]
358struct MyErr;
359```
360
361#### ... snippets
362
363Along with its general error handling and reporting features, `miette` also
364includes facilities for adding error spans/annotations/labels to your
365output. This can be very useful when an error is syntax-related, but you can
366even use it to print out sections of your own source code!
367
368To achieve this, `miette` defines its own lightweight [`SourceSpan`] type.
369This is a basic byte-offset and length into an associated [`SourceCode`]
370and, along with the latter, gives `miette` all the information it needs to
371pretty-print some snippets! You can also use your own `Into<SourceSpan>`
372types as label spans.
373
374The easiest way to define errors like this is to use the
375`derive(Diagnostic)` macro:
376
377```rust
378use miette::{Diagnostic, SourceSpan};
379use thiserror::Error;
380
381#[derive(Diagnostic, Debug, Error)]
382#[error("oops")]
383#[diagnostic(code(my_lib::random_error))]
384pub struct MyErrorType {
385 // The `Source` that miette will use.
386 #[source_code]
387 src: String,
388
389 // This will underline/mark the specific code inside the larger
390 // snippet context.
391 #[label = "This is the highlight"]
392 err_span: SourceSpan,
393
394 // You can add as many labels as you want.
395 // They'll be rendered sequentially.
396 #[label("This is bad")]
397 snip2: (usize, usize), // `(usize, usize)` is `Into<SourceSpan>`!
398
399 // Snippets can be optional, by using Option:
400 #[label("some text")]
401 snip3: Option<SourceSpan>,
402
403 // with or without label text
404 #[label]
405 snip4: Option<SourceSpan>,
406}
407```
408
409##### ... help text
410`miette` provides two facilities for supplying help text for your errors:
411
412The first is the `#[help()]` format attribute that applies to structs or
413enum variants:
414
415```rust
416use miette::Diagnostic;
417use thiserror::Error;
418
419#[derive(Debug, Diagnostic, Error)]
420#[error("welp")]
421#[diagnostic(help("try doing this instead"))]
422struct Foo;
423```
424
425The other is by programmatically supplying the help text as a field to
426your diagnostic:
427
428```rust
429use miette::Diagnostic;
430use thiserror::Error;
431
432#[derive(Debug, Diagnostic, Error)]
433#[error("welp")]
434#[diagnostic()]
435struct Foo {
436 #[help]
437 advice: Option<String>, // Can also just be `String`
438}
439
440let err = Foo {
441 advice: Some("try doing this instead".to_string()),
442};
443```
444
445#### ... multiple related errors
446
447`miette` supports collecting multiple errors into a single diagnostic, and
448printing them all together nicely.
449
450To do so, use the `#[related]` tag on any `IntoIter` field in your
451`Diagnostic` type:
452
453```rust
454use miette::Diagnostic;
455use thiserror::Error;
456
457#[derive(Debug, Error, Diagnostic)]
458#[error("oops")]
459struct MyError {
460 #[related]
461 others: Vec<MyError>,
462}
463```
464
465#### ... delayed source code
466
467Sometimes it makes sense to add source code to the error message later.
468One option is to use [`with_source_code()`](Report::with_source_code)
469method for that:
470
471```rust
472use miette::{Diagnostic, SourceSpan};
473use thiserror::Error;
474
475#[derive(Diagnostic, Debug, Error)]
476#[error("oops")]
477#[diagnostic()]
478pub struct MyErrorType {
479 // Note: label but no source code
480 #[label]
481 err_span: SourceSpan,
482}
483
484fn do_something() -> miette::Result<()> {
485 // This function emits actual error with label
486 return Err(MyErrorType {
487 err_span: (7..11).into(),
488 })?;
489}
490
491fn main() -> miette::Result<()> {
492 do_something().map_err(|error| {
493 // And this code provides the source code for inner error
494 error.with_source_code(String::from("source code"))
495 })
496}
497```
498
499Also source code can be provided by a wrapper type. This is especially
500useful in combination with `related`, when multiple errors should be
501emitted at the same time:
502
503```rust
504use miette::{Diagnostic, Report, SourceSpan};
505use thiserror::Error;
506
507#[derive(Diagnostic, Debug, Error)]
508#[error("oops")]
509#[diagnostic()]
510pub struct InnerError {
511 // Note: label but no source code
512 #[label]
513 err_span: SourceSpan,
514}
515
516#[derive(Diagnostic, Debug, Error)]
517#[error("oops: multiple errors")]
518#[diagnostic()]
519pub struct MultiError {
520 // Note source code by no labels
521 #[source_code]
522 source_code: String,
523 // The source code above is used for these errors
524 #[related]
525 related: Vec<InnerError>,
526}
527
528fn do_something() -> Result<(), Vec<InnerError>> {
529 Err(vec![
530 InnerError {
531 err_span: (0..6).into(),
532 },
533 InnerError {
534 err_span: (7..11).into(),
535 },
536 ])
537}
538
539fn main() -> miette::Result<()> {
540 do_something().map_err(|err_list| MultiError {
541 source_code: "source code".into(),
542 related: err_list,
543 })?;
544 Ok(())
545}
546```
547
548#### ... Diagnostic-based error sources.
549
550When one uses the `#[source]` attribute on a field, that usually comes
551from `thiserror`, and implements a method for
552[`std::error::Error::source`]. This works in many cases, but it's lossy:
553if the source of the diagnostic is a diagnostic itself, the source will
554simply be treated as an `std::error::Error`.
555
556While this has no effect on the existing _reporters_, since they don't use
557that information right now, APIs who might want this information will have
558no access to it.
559
560If it's important for you for this information to be available to users,
561you can use `#[diagnostic_source]` alongside `#[source]`. Not that you
562will likely want to use _both_:
563
564```rust
565use miette::Diagnostic;
566use thiserror::Error;
567
568#[derive(Debug, Diagnostic, Error)]
569#[error("MyError")]
570struct MyError {
571 #[source]
572 #[diagnostic_source]
573 the_cause: OtherError,
574}
575
576#[derive(Debug, Diagnostic, Error)]
577#[error("OtherError")]
578struct OtherError;
579```
580
581#### ... handler options
582
583[`MietteHandler`] is the default handler, and is very customizable. In
584most cases, you can simply use [`MietteHandlerOpts`] to tweak its behavior
585instead of falling back to your own custom handler.
586
587Usage is like so:
588
589```rust
590miette::set_hook(Box::new(|_| {
591 Box::new(
592 miette::MietteHandlerOpts::new()
593 .terminal_links(true)
594 .unicode(false)
595 .context_lines(3)
596 .tab_width(4)
597 .build(),
598 )
599}))
600
601```
602
603See the docs for [`MietteHandlerOpts`] for more details on what you can
604customize!
605
606#### ... dynamic diagnostics
607
608If you...
609- ...don't know all the possible errors upfront
610- ...need to serialize/deserialize errors
611then you may want to use [`miette!`], [`diagnostic!`] macros or
612[`MietteDiagnostic`] directly to create diagnostic on the fly.
613
614```rust
615
616let source = "2 + 2 * 2 = 8".to_string();
617let report = miette!(
618 labels = vec[
619 LabeledSpan::at(12..13, "this should be 6"),
620 ],
621 help = "'*' has greater precedence than '+'",
622 "Wrong answer"
623).with_source_code(source);
624println!("{:?}", report)
625```
626
627### Acknowledgements
628
629`miette` was not developed in a void. It owes enormous credit to various
630other projects and their authors:
631
632- [`anyhow`](http://crates.io/crates/anyhow) and [`color-eyre`](https://crates.io/crates/color-eyre):
633 these two enormously influential error handling libraries have pushed
634 forward the experience of application-level error handling and error
635 reporting. `miette`'s `Report` type is an attempt at a very very rough
636 version of their `Report` types.
637- [`thiserror`](https://crates.io/crates/thiserror) for setting the standard
638 for library-level error definitions, and for being the inspiration behind
639 `miette`'s derive macro.
640- `rustc` and [@estebank](https://github.com/estebank) for their
641 state-of-the-art work in compiler diagnostics.
642- [`ariadne`](https://crates.io/crates/ariadne) for pushing forward how
643 _pretty_ these diagnostics can really look!
644
645### License
646
647`miette` is released to the Rust community under the [Apache license
6482.0](./LICENSE).
649
650It also includes code taken from [`eyre`](https://github.com/yaahc/eyre),
651and some from [`thiserror`](https://github.com/dtolnay/thiserror), also
652under the Apache License. Some code is taken from
653[`ariadne`](https://github.com/zesterer/ariadne), which is MIT licensed.
654
655[`miette!`]: https://docs.rs/miette/latest/miette/macro.miette.html
656[`diagnostic!`]: https://docs.rs/miette/latest/miette/macro.diagnostic.html
657[`std::error::Error`]: https://doc.rust-lang.org/nightly/std/error/trait.Error.html
658[`Diagnostic`]: https://docs.rs/miette/latest/miette/trait.Diagnostic.html
659[`IntoDiagnostic`]: https://docs.rs/miette/latest/miette/trait.IntoDiagnostic.html
660[`MietteHandlerOpts`]: https://docs.rs/miette/latest/miette/struct.MietteHandlerOpts.html
661[`MietteHandler`]: https://docs.rs/miette/latest/miette/struct.MietteHandler.html
662[`MietteDiagnostic`]: https://docs.rs/miette/latest/miette/struct.MietteDiagnostic.html
663[`Report`]: https://docs.rs/miette/latest/miette/struct.Report.html
664[`ReportHandler`]: https://docs.rs/miette/latest/miette/trait.ReportHandler.html
665[`Result`]: https://docs.rs/miette/latest/miette/type.Result.html
666[`SourceCode`]: https://docs.rs/miette/latest/miette/trait.SourceCode.html
667[`SourceSpan`]: https://docs.rs/miette/latest/miette/struct.SourceSpan.html
668