{"id":13599837,"url":"https://github.com/zkat/miette","last_synced_at":"2025-05-14T12:05:22.783Z","repository":{"id":37488211,"uuid":"392161911","full_name":"zkat/miette","owner":"zkat","description":"Fancy extension for std::error::Error with pretty, detailed diagnostic printing.","archived":false,"fork":false,"pushed_at":"2025-04-27T04:53:46.000Z","size":1888,"stargazers_count":2197,"open_issues_count":87,"forks_count":127,"subscribers_count":15,"default_branch":"main","last_synced_at":"2025-05-07T11:42:01.369Z","etag":null,"topics":["error-handling","error-reporting","hacktoberfest","hacktoberfest2021","rust"],"latest_commit_sha":null,"homepage":"https://docs.rs/miette","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zkat.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":["zkat"],"patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":null}},"created_at":"2021-08-03T02:30:49.000Z","updated_at":"2025-05-06T18:03:24.000Z","dependencies_parsed_at":"2024-01-04T19:42:33.132Z","dependency_job_id":"dcf12cb1-328a-4fba-b8c5-e214eaadf3ad","html_url":"https://github.com/zkat/miette","commit_stats":{"total_commits":525,"total_committers":71,"mean_commits":7.394366197183099,"dds":0.2666666666666667,"last_synced_commit":"5f441d011560a091fe5d6a6cdb05f09acf622d36"},"previous_names":[],"tags_count":99,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zkat%2Fmiette","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zkat%2Fmiette/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zkat%2Fmiette/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zkat%2Fmiette/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zkat","download_url":"https://codeload.github.com/zkat/miette/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254140738,"owners_count":22021218,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["error-handling","error-reporting","hacktoberfest","hacktoberfest2021","rust"],"created_at":"2024-08-01T17:01:13.333Z","updated_at":"2025-05-14T12:05:22.694Z","avatar_url":"https://github.com/zkat.png","language":"Rust","readme":"\n# `miette`\n\nYou run miette? You run her code like the software? Oh. Oh! Error code for\ncoder! Error code for One Thousand Lines!\n\n### About\n\n`miette` is a diagnostic library for Rust. It includes a series of\ntraits/protocols that allow you to hook into its error reporting facilities,\nand even write your own error reports! It lets you define error types that\ncan print out like this (or in any format you like!):\n\n\u003cimg 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:\n\\\nError: Received some bad JSON from the source. Unable to parse.\n    Caused by: missing field `foo` at line 1 column 1700\n\\\nBegin snippet for https://api.nuget.org/v3/registration5-gz-semver2/json.net/index.json starting\nat line 1, column 1659\n\\\nsnippet line 1: gs\u0026quot;:[\u0026quot;json\u0026quot;],\u0026quot;title\u0026quot;:\u0026quot;\u0026quot;,\u0026quot;version\u0026quot;:\u0026quot;1.0.0\u0026quot;},\u0026quot;packageContent\u0026quot;:\u0026quot;https://api.nuget.o\n    highlight starting at line 1, column 1699: last parsing location\n\\\ndiagnostic help: This is a bug. It might be in ruget, or it might be in the\nsource you're using, but it's definitely a bug and should be reported.\ndiagnostic error code: ruget::api::bad_json\n\" /\u003e\n\n\u003e **NOTE: You must enable the `\"fancy\"` crate feature to get fancy report\n\u003e output like in the screenshots above.** You should only do this in your\n\u003e toplevel crate, as the fancy feature pulls in a number of dependencies that\n\u003e libraries and such might not want.\n\n### Table of Contents \u003c!-- omit in toc --\u003e\n\n- [About](#about)\n- [Features](#features)\n- [Installing](#installing)\n- [Example](#example)\n- [Using](#using)\n  - [... in libraries](#-in-libraries)\n  - [... in application code](#-in-application-code)\n  - [... in `main()`](#-in-main)\n  - [... diagnostic code URLs](#-diagnostic-code-urls)\n  - [... snippets](#-snippets)\n  - [... help text](#-help-text)\n  - [... severity level](#-severity-level)\n  - [... multiple related errors](#-multiple-related-errors)\n  - [... delayed source code](#-delayed-source-code)\n  - [... handler options](#-handler-options)\n  - [... dynamic diagnostics](#-dynamic-diagnostics)\n  - [... syntax highlighting](#-syntax-highlighting)\n  - [... primary label](#-primary-label)\n  - [... collection of labels](#-collection-of-labels)\n- [Acknowledgements](#acknowledgements)\n- [License](#license)\n\n### Features\n\n- Generic [`Diagnostic`] protocol, compatible (and dependent on)\n  [`std::error::Error`].\n- Unique error codes on every [`Diagnostic`].\n- Custom links to get more details on error codes.\n- Super handy derive macro for defining diagnostic metadata.\n- Replacements for [`anyhow`](https://docs.rs/anyhow)/[`eyre`](https://docs.rs/eyre)\n  types [`Result`], [`Report`] and the [`miette!`] macro for the\n  `anyhow!`/`eyre!` macros.\n- Generic support for arbitrary [`SourceCode`]s for snippet data, with\n  default support for `String`s included.\n\nThe `miette` crate also comes bundled with a default [`ReportHandler`] with\nthe following features:\n\n- Fancy graphical [diagnostic output](#about), using ANSI/Unicode text\n- single- and multi-line highlighting support\n- Screen reader/braille support, gated on [`NO_COLOR`](http://no-color.org/),\n  and other heuristics.\n- Fully customizable graphical theming (or overriding the printers\n  entirely).\n- Cause chain printing\n- Turns diagnostic codes into links in [supported terminals](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda).\n\n### Installing\n\n```sh\n$ cargo add miette\n```\n\nIf you want to use the fancy printer in all these screenshots:\n\n```sh\n$ cargo add miette --features fancy\n```\n\n### Example\n\n```rust\n/*\nYou can derive a `Diagnostic` from any `std::error::Error` type.\n\n`thiserror` is a great way to define them, and plays nicely with `miette`!\n*/\nuse miette::{Diagnostic, NamedSource, SourceSpan};\nuse thiserror::Error;\n\n#[derive(Error, Debug, Diagnostic)]\n#[error(\"oops!\")]\n#[diagnostic(\n    code(oops::my::bad),\n    url(docsrs),\n    help(\"try doing it better next time?\")\n)]\nstruct MyBad {\n    // The Source that we're gonna be printing snippets out of.\n    // This can be a String if you don't have or care about file names.\n    #[source_code]\n    src: NamedSource\u003cString\u003e,\n    // Snippets and highlights can be included in the diagnostic!\n    #[label(\"This bit here\")]\n    bad_bit: SourceSpan,\n}\n\n/*\nNow let's define a function!\n\nUse this `Result` type (or its expanded version) as the return type\nthroughout your app (but NOT your libraries! Those should always return\nconcrete types!).\n*/\nuse miette::Result;\nfn this_fails() -\u003e Result\u003c()\u003e {\n    // You can use plain strings as a `Source`, or anything that implements\n    // the one-method `Source` trait.\n    let src = \"source\\n  text\\n    here\".to_string();\n\n    Err(MyBad {\n        src: NamedSource::new(\"bad_file.rs\", src),\n        bad_bit: (9, 4).into(),\n    })?;\n\n    Ok(())\n}\n\n/*\nNow to get everything printed nicely, just return a `Result\u003c()\u003e`\nand you're all set!\n\nNote: You can swap out the default reporter for a custom one using\n`miette::set_hook()`\n*/\nfn pretend_this_is_main() -\u003e Result\u003c()\u003e {\n    // kaboom~\n    this_fails()?;\n\n    Ok(())\n}\n```\n\nAnd this is the output you'll get if you run this program:\n\n\u003cimg src=\"https://raw.githubusercontent.com/zkat/miette/main/images/single-line-example.png\" alt=\"\nNarratable printout:\n\\\ndiagnostic error code: oops::my::bad (link)\nError: oops!\n\\\nBegin snippet for bad_file.rs starting\nat line 2, column 3\n\\\nsnippet line 1: source\n\\\nsnippet line 2:  text\n    highlight starting at line 1, column 3: This bit here\n\\\nsnippet line 3: here\n\\\ndiagnostic help: try doing it better next time?\"\u003e\n\n### Using\n\n#### ... in libraries\n\n`miette` is _fully compatible_ with library usage. Consumers who don't know\nabout, or don't want, `miette` features can safely use its error types as\nregular [`std::error::Error`].\n\nWe highly recommend using something like [`thiserror`](https://docs.rs/thiserror)\nto define unique error types and error wrappers for your library.\n\nWhile `miette` integrates smoothly with `thiserror`, it is _not required_.\nIf you don't want to use the [`Diagnostic`] derive macro, you can implement\nthe trait directly, just like with `std::error::Error`.\n\n```rust\n// lib/error.rs\nuse miette::{Diagnostic, SourceSpan};\nuse thiserror::Error;\n\n#[derive(Error, Diagnostic, Debug)]\npub enum MyLibError {\n    #[error(transparent)]\n    #[diagnostic(code(my_lib::io_error))]\n    IoError(#[from] std::io::Error),\n\n    #[error(\"Oops it blew up\")]\n    #[diagnostic(code(my_lib::bad_code))]\n    BadThingHappened,\n\n    #[error(transparent)]\n    // Use `#[diagnostic(transparent)]` to wrap another [`Diagnostic`]. You won't see labels otherwise\n    #[diagnostic(transparent)]\n    AnotherError(#[from] AnotherError),\n}\n\n#[derive(Error, Diagnostic, Debug)]\n#[error(\"another error\")]\npub struct AnotherError {\n   #[label(\"here\")]\n   pub at: SourceSpan\n}\n```\n\nThen, return this error type from all your fallible public APIs. It's a best\npractice to wrap any \"external\" error types in your error `enum` instead of\nusing something like [`Report`] in a library.\n\n#### ... in application code\n\nApplication code tends to work a little differently than libraries. You\ndon't always need or care to define dedicated error wrappers for errors\ncoming from external libraries and tools.\n\nFor this situation, `miette` includes two tools: [`Report`] and\n[`IntoDiagnostic`]. They work in tandem to make it easy to convert regular\n`std::error::Error`s into [`Diagnostic`]s. Additionally, there's a\n[`Result`] type alias that you can use to be more terse.\n\nWhen dealing with non-`Diagnostic` types, you'll want to\n`.into_diagnostic()` them:\n\n```rust\n// my_app/lib/my_internal_file.rs\nuse miette::{IntoDiagnostic, Result};\nuse semver::Version;\n\npub fn some_tool() -\u003e Result\u003cVersion\u003e {\n    \"1.2.x\".parse().into_diagnostic()\n}\n```\n\n`miette` also includes an `anyhow`/`eyre`-style `Context`/`WrapErr` traits\nthat you can import to add ad-hoc context messages to your `Diagnostic`s, as\nwell, though you'll still need to use `.into_diagnostic()` to make use of\nit:\n\n```rust\n// my_app/lib/my_internal_file.rs\nuse miette::{IntoDiagnostic, Result, WrapErr};\nuse semver::Version;\n\npub fn some_tool() -\u003e Result\u003cVersion\u003e {\n    \"1.2.x\"\n        .parse()\n        .into_diagnostic()\n        .wrap_err(\"Parsing this tool's semver version failed.\")\n}\n```\n\nTo construct your own simple adhoc error use the [`miette!`] macro:\n```rust\n// my_app/lib/my_internal_file.rs\nuse miette::{miette, Result};\nuse semver::Version;\n\npub fn some_tool() -\u003e Result\u003cVersion\u003e {\n    let version = \"1.2.x\";\n    version\n        .parse()\n        .map_err(|_| miette!(\"Invalid version {}\", version))\n}\n```\nThere are also similar [bail!] and [ensure!] macros.\n\n#### ... in `main()`\n\n`main()` is just like any other part of your application-internal code. Use\n`Result` as your return value, and it will pretty-print your diagnostics\nautomatically.\n\n\u003e **NOTE:** You must enable the `\"fancy\"` crate feature to get fancy report\n\u003e output like in the screenshots here.** You should only do this in your\n\u003e toplevel crate, as the fancy feature pulls in a number of dependencies that\n\u003e libraries and such might not want.\n\n```rust\nuse miette::{IntoDiagnostic, Result};\nuse semver::Version;\n\nfn pretend_this_is_main() -\u003e Result\u003c()\u003e {\n    let version: Version = \"1.2.x\".parse().into_diagnostic()?;\n    println!(\"{}\", version);\n    Ok(())\n}\n```\n\nPlease note: in order to get fancy diagnostic rendering with all the pretty\ncolors and arrows, you should install `miette` with the `fancy` feature\nenabled:\n\n```toml\nmiette = { version = \"X.Y.Z\", features = [\"fancy\"] }\n```\n\nAnother way to display a diagnostic is by printing them using the debug formatter.\nThis is, in fact, what returning diagnostics from main ends up doing.\nTo do it yourself, you can write the following:\n\n```rust\nuse miette::{IntoDiagnostic, Result};\nuse semver::Version;\n\nfn just_a_random_function() {\n    let version_result: Result\u003cVersion\u003e = \"1.2.x\".parse().into_diagnostic();\n    match version_result {\n        Err(e) =\u003e println!(\"{:?}\", e),\n        Ok(version) =\u003e println!(\"{}\", version),\n    }\n}\n```\n\n#### ... diagnostic code URLs\n\n`miette` supports providing a URL for individual diagnostics. This URL will\nbe displayed as an actual link in supported terminals, like so:\n\n\u003cimg\nsrc=\"https://raw.githubusercontent.com/zkat/miette/main/images/code_linking.png\"\nalt=\" Example showing the graphical report printer for miette\npretty-printing an error code. The code is underlined and followed by text\nsaying to 'click here'. A hover tooltip shows a full-fledged URL that can be\nCtrl+Clicked to open in a browser.\n\\\nThis feature is also available in the narratable printer. It will add a line\nafter printing the error code showing a plain URL that you can visit.\n\"\u003e\n\nTo use this, you can add a `url()` sub-param to your `#[diagnostic]`\nattribute:\n\n```rust\nuse miette::Diagnostic;\nuse thiserror::Error;\n\n#[derive(Error, Diagnostic, Debug)]\n#[error(\"kaboom\")]\n#[diagnostic(\n    code(my_app::my_error),\n    // You can do formatting!\n    url(\"https://my_website.com/error_codes#{}\", self.code().unwrap())\n)]\nstruct MyErr;\n```\n\nAdditionally, if you're developing a library and your error type is exported\nfrom your crate's top level, you can use a special `url(docsrs)` option\ninstead of manually constructing the URL. This will automatically create a\nlink to this diagnostic on `docs.rs`, so folks can just go straight to your\n(very high quality and detailed!) documentation on this diagnostic:\n\n```rust\nuse miette::Diagnostic;\nuse thiserror::Error;\n\n#[derive(Error, Diagnostic, Debug)]\n#[diagnostic(\n    code(my_app::my_error),\n    // Will link users to https://docs.rs/my_crate/0.0.0/my_crate/struct.MyErr.html\n    url(docsrs)\n)]\n#[error(\"kaboom\")]\nstruct MyErr;\n```\n\n#### ... snippets\n\nAlong with its general error handling and reporting features, `miette` also\nincludes facilities for adding error spans/annotations/labels to your\noutput. This can be very useful when an error is syntax-related, but you can\neven use it to print out sections of your own source code!\n\nTo achieve this, `miette` defines its own lightweight [`SourceSpan`] type.\nThis is a basic byte-offset and length into an associated [`SourceCode`]\nand, along with the latter, gives `miette` all the information it needs to\npretty-print some snippets! You can also use your own `Into\u003cSourceSpan\u003e`\ntypes as label spans.\n\nThe easiest way to define errors like this is to use the\n`derive(Diagnostic)` macro:\n\n```rust\nuse miette::{Diagnostic, SourceSpan};\nuse thiserror::Error;\n\n#[derive(Diagnostic, Debug, Error)]\n#[error(\"oops\")]\n#[diagnostic(code(my_lib::random_error))]\npub struct MyErrorType {\n    // The `Source` that miette will use.\n    #[source_code]\n    src: String,\n\n    // This will underline/mark the specific code inside the larger\n    // snippet context.\n    #[label = \"This is the highlight\"]\n    err_span: SourceSpan,\n\n    // You can add as many labels as you want.\n    // They'll be rendered sequentially.\n    #[label(\"This is bad\")]\n    snip2: (usize, usize), // `(usize, usize)` is `Into\u003cSourceSpan\u003e`!\n\n    // Snippets can be optional, by using Option:\n    #[label(\"some text\")]\n    snip3: Option\u003cSourceSpan\u003e,\n\n    // with or without label text\n    #[label]\n    snip4: Option\u003cSourceSpan\u003e,\n}\n```\n\n#### ... help text\n`miette` provides two facilities for supplying help text for your errors:\n\nThe first is the `#[help()]` format attribute that applies to structs or\nenum variants:\n\n```rust\nuse miette::Diagnostic;\nuse thiserror::Error;\n\n#[derive(Debug, Diagnostic, Error)]\n#[error(\"welp\")]\n#[diagnostic(help(\"try doing this instead\"))]\nstruct Foo;\n```\n\nThe other is by programmatically supplying the help text as a field to\nyour diagnostic:\n\n```rust\nuse miette::Diagnostic;\nuse thiserror::Error;\n\n#[derive(Debug, Diagnostic, Error)]\n#[error(\"welp\")]\n#[diagnostic()]\nstruct Foo {\n    #[help]\n    advice: Option\u003cString\u003e, // Can also just be `String`\n}\n\nlet err = Foo {\n    advice: Some(\"try doing this instead\".to_string()),\n};\n```\n\n#### ... severity level\n`miette` provides a way to set the severity level of a diagnostic.\n\n```rust\nuse miette::Diagnostic;\nuse thiserror::Error;\n\n#[derive(Debug, Diagnostic, Error)]\n#[error(\"welp\")]\n#[diagnostic(severity(Warning))]\nstruct Foo;\n```\n\n#### ... multiple related errors\n\n`miette` supports collecting multiple errors into a single diagnostic, and\nprinting them all together nicely.\n\nTo do so, use the `#[related]` tag on any `IntoIter` field in your\n`Diagnostic` type:\n\n```rust\nuse miette::Diagnostic;\nuse thiserror::Error;\n\n#[derive(Debug, Error, Diagnostic)]\n#[error(\"oops\")]\nstruct MyError {\n    #[related]\n    others: Vec\u003cMyError\u003e,\n}\n```\n\n#### ... delayed source code\n\nSometimes it makes sense to add source code to the error message later.\nOne option is to use [`with_source_code()`](Report::with_source_code)\nmethod for that:\n\n```rust\nuse miette::{Diagnostic, SourceSpan};\nuse thiserror::Error;\n\n#[derive(Diagnostic, Debug, Error)]\n#[error(\"oops\")]\n#[diagnostic()]\npub struct MyErrorType {\n    // Note: label but no source code\n    #[label]\n    err_span: SourceSpan,\n}\n\nfn do_something() -\u003e miette::Result\u003c()\u003e {\n    // This function emits actual error with label\n    return Err(MyErrorType {\n        err_span: (7..11).into(),\n    })?;\n}\n\nfn main() -\u003e miette::Result\u003c()\u003e {\n    do_something().map_err(|error| {\n        // And this code provides the source code for inner error\n        error.with_source_code(String::from(\"source code\"))\n    })\n}\n```\n\nAlso source code can be provided by a wrapper type. This is especially\nuseful in combination with `related`, when multiple errors should be\nemitted at the same time:\n\n```rust\nuse miette::{Diagnostic, Report, SourceSpan};\nuse thiserror::Error;\n\n#[derive(Diagnostic, Debug, Error)]\n#[error(\"oops\")]\n#[diagnostic()]\npub struct InnerError {\n    // Note: label but no source code\n    #[label]\n    err_span: SourceSpan,\n}\n\n#[derive(Diagnostic, Debug, Error)]\n#[error(\"oops: multiple errors\")]\n#[diagnostic()]\npub struct MultiError {\n    // Note source code by no labels\n    #[source_code]\n    source_code: String,\n    // The source code above is used for these errors\n    #[related]\n    related: Vec\u003cInnerError\u003e,\n}\n\nfn do_something() -\u003e Result\u003c(), Vec\u003cInnerError\u003e\u003e {\n    Err(vec![\n        InnerError {\n            err_span: (0..6).into(),\n        },\n        InnerError {\n            err_span: (7..11).into(),\n        },\n    ])\n}\n\nfn main() -\u003e miette::Result\u003c()\u003e {\n    do_something().map_err(|err_list| MultiError {\n        source_code: \"source code\".into(),\n        related: err_list,\n    })?;\n    Ok(())\n}\n```\n\n#### ... Diagnostic-based error sources.\n\nWhen one uses the `#[source]` attribute on a field, that usually comes\nfrom `thiserror`, and implements a method for\n[`std::error::Error::source`]. This works in many cases, but it's lossy:\nif the source of the diagnostic is a diagnostic itself, the source will\nsimply be treated as an `std::error::Error`.\n\nWhile this has no effect on the existing _reporters_, since they don't use\nthat information right now, APIs who might want this information will have\nno access to it.\n\nIf it's important for you for this information to be available to users,\nyou can use `#[diagnostic_source]` alongside `#[source]`. Not that you\nwill likely want to use _both_:\n\n```rust\nuse miette::Diagnostic;\nuse thiserror::Error;\n\n#[derive(Debug, Diagnostic, Error)]\n#[error(\"MyError\")]\nstruct MyError {\n    #[source]\n    #[diagnostic_source]\n    the_cause: OtherError,\n}\n\n#[derive(Debug, Diagnostic, Error)]\n#[error(\"OtherError\")]\nstruct OtherError;\n```\n\n#### ... handler options\n\n[`MietteHandler`] is the default handler, and is very customizable. In\nmost cases, you can simply use [`MietteHandlerOpts`] to tweak its behavior\ninstead of falling back to your own custom handler.\n\nUsage is like so:\n\n```rust\nmiette::set_hook(Box::new(|_| {\n    Box::new(\n        miette::MietteHandlerOpts::new()\n            .terminal_links(true)\n            .unicode(false)\n            .context_lines(3)\n            .tab_width(4)\n            .break_words(true)\n            .build(),\n    )\n}))\n\n```\n\nSee the docs for [`MietteHandlerOpts`] for more details on what you can\ncustomize!\n\n#### ... dynamic diagnostics\n\nIf you...\n- ...don't know all the possible errors upfront\n- ...need to serialize/deserialize errors\n  then you may want to use [`miette!`], [`diagnostic!`] macros or\n  [`MietteDiagnostic`] directly to create diagnostic on the fly.\n\n```rust\n\nlet source = \"2 + 2 * 2 = 8\".to_string();\nlet report = miette!(\n  labels = vec![\n      LabeledSpan::at(12..13, \"this should be 6\"),\n  ],\n  help = \"'*' has greater precedence than '+'\",\n  \"Wrong answer\"\n).with_source_code(source);\nprintln!(\"{:?}\", report)\n```\n\n#### ... syntax highlighting\n\n`miette` can be configured to highlight syntax in source code snippets.\n\n\u003c!-- TODO: screenshot goes here once default Theme is decided --\u003e\n\nTo use the built-in highlighting functionality, you must enable the\n`syntect-highlighter` crate feature. When this feature is enabled, `miette` will\nautomatically use the [`syntect`] crate to highlight the `#[source_code]`\nfield of your [`Diagnostic`].\n\nSyntax detection with [`syntect`] is handled by checking 2 methods on the [`SpanContents`] trait, in order:\n* [`language()`](SpanContents::language) - Provides the name of the language\n  as a string. For example `\"Rust\"` will indicate Rust syntax highlighting.\n  You can set the language of the [`SpanContents`] produced by a\n  [`NamedSource`] via the [`with_language`](NamedSource::with_language)\n  method.\n* [`name()`](SpanContents::name) - In the absence of an explicitly set\n  language, the name is assumed to contain a file name or file path.\n  The highlighter will check for a file extension at the end of the name and\n  try to guess the syntax from that.\n\nIf you want to use a custom highlighter, you can provide a custom\nimplementation of the [`Highlighter`](highlighters::Highlighter)\ntrait to [`MietteHandlerOpts`] by calling the\n[`with_syntax_highlighting`](MietteHandlerOpts::with_syntax_highlighting)\nmethod. See the [`highlighters`] module docs for more details.\n\n#### ... primary label\n\nYou can use the `primary` parameter to `label` to indicate that the label\nis the primary label.\n\n```rust\n#[derive(Debug, Diagnostic, Error)]\n#[error(\"oops!\")]\nstruct MyError {\n    #[label(primary, \"main issue\")]\n    primary_span: SourceSpan,\n\n    #[label(\"other label\")]\n    other_span: SourceSpan,\n}\n```\n\nThe `primary` parameter can be used at most once:\n\n```rust\n#[derive(Debug, Diagnostic, Error)]\n#[error(\"oops!\")]\nstruct MyError {\n    #[label(primary, \"main issue\")]\n    primary_span: SourceSpan,\n\n    #[label(primary, \"other label\")] // Error: Cannot have more than one primary label.\n    other_span: SourceSpan,\n}\n```\n\n#### ... collection of labels\n\nWhen the number of labels is unknown, you can use a collection of `SourceSpan`\n(or any type convertible into `SourceSpan`). For this, add the `collection`\nparameter to `label` and use any type than can be iterated over for the field.\n\n```rust\n#[derive(Debug, Diagnostic, Error)]\n#[error(\"oops!\")]\nstruct MyError {\n    #[label(\"main issue\")]\n    primary_span: SourceSpan,\n\n    #[label(collection, \"related to this\")]\n    other_spans: Vec\u003cRange\u003cusize\u003e\u003e,\n}\n\nlet report: miette::Report = MyError {\n    primary_span: (6, 9).into(),\n    other_spans: vec![19..26, 30..41],\n}.into();\n\nprintln!(\"{:?}\", report.with_source_code(\"About something or another or yet another ...\".to_string()));\n```\n\nA collection can also be of `LabeledSpan` if you want to have different text\nfor different labels. Labels with no text will use the one from the `label`\nattribute\n\n```rust\n#[derive(Debug, Diagnostic, Error)]\n#[error(\"oops!\")]\nstruct MyError {\n    #[label(\"main issue\")]\n    primary_span: SourceSpan,\n\n    #[label(collection, \"related to this\")]\n    other_spans: Vec\u003cLabeledSpan\u003e, // LabeledSpan\n}\n\nlet report: miette::Report = MyError {\n    primary_span: (6, 9).into(),\n    other_spans: vec![\n        LabeledSpan::new(None, 19, 7), // Use default text `related to this`\n        LabeledSpan::new(Some(\"and also this\".to_string()), 30, 11), // Use specific text\n    ],\n}.into();\n\nprintln!(\"{:?}\", report.with_source_code(\"About something or another or yet another ...\".to_string()));\n```\n\n### MSRV\n\nThis crate requires rustc 1.70.0 or later.\n\n### Acknowledgements\n\n`miette` was not developed in a void. It owes enormous credit to various\nother projects and their authors:\n\n- [`anyhow`](http://crates.io/crates/anyhow) and [`color-eyre`](https://crates.io/crates/color-eyre):\n  these two enormously influential error handling libraries have pushed\n  forward the experience of application-level error handling and error\n  reporting. `miette`'s `Report` type is an attempt at a very very rough\n  version of their `Report` types.\n- [`thiserror`](https://crates.io/crates/thiserror) for setting the standard\n  for library-level error definitions, and for being the inspiration behind\n  `miette`'s derive macro.\n- `rustc` and [@estebank](https://github.com/estebank) for their\n  state-of-the-art work in compiler diagnostics.\n- [`ariadne`](https://crates.io/crates/ariadne) for pushing forward how\n  _pretty_ these diagnostics can really look!\n\n### License\n\n`miette` is released to the Rust community under the [Apache license\n2.0](./LICENSE).\n\nIt also includes code taken from [`eyre`](https://github.com/yaahc/eyre),\nand some from [`thiserror`](https://github.com/dtolnay/thiserror), also\nunder the Apache License. Some code is taken from\n[`ariadne`](https://github.com/zesterer/ariadne), which is MIT licensed.\n\n[`miette!`]: https://docs.rs/miette/latest/miette/macro.miette.html\n[`diagnostic!`]: https://docs.rs/miette/latest/miette/macro.diagnostic.html\n[`std::error::Error`]: https://doc.rust-lang.org/nightly/std/error/trait.Error.html\n[`Diagnostic`]: https://docs.rs/miette/latest/miette/trait.Diagnostic.html\n[`IntoDiagnostic`]: https://docs.rs/miette/latest/miette/trait.IntoDiagnostic.html\n[`MietteHandlerOpts`]: https://docs.rs/miette/latest/miette/struct.MietteHandlerOpts.html\n[`MietteHandler`]: https://docs.rs/miette/latest/miette/struct.MietteHandler.html\n[`MietteDiagnostic`]: https://docs.rs/miette/latest/miette/struct.MietteDiagnostic.html\n[`Report`]: https://docs.rs/miette/latest/miette/struct.Report.html\n[`ReportHandler`]: https://docs.rs/miette/latest/miette/trait.ReportHandler.html\n[`Result`]: https://docs.rs/miette/latest/miette/type.Result.html\n[`SourceCode`]: https://docs.rs/miette/latest/miette/trait.SourceCode.html\n[`SourceSpan`]: https://docs.rs/miette/latest/miette/struct.SourceSpan.html\n","funding_links":["https://github.com/sponsors/zkat"],"categories":["Rust"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzkat%2Fmiette","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzkat%2Fmiette","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzkat%2Fmiette/lists"}