### Advanced miette! Examples Source: https://github.com/zkat/miette/blob/main/_autodocs/macros.md Demonstrates various configurations including simple messages, labels, and full diagnostic fields. ```rust use miette::{miette, Severity}; // Simple message let err = miette!("Parse failed"); // With labels and help let err = miette!( labels = vec![], help = "Check the file format", "Invalid format" ); // With all fields let err = miette!( code = "app::parse_error", severity = Severity::Error, help = "See documentation for details", url = "https://docs.example.com/errors", labels = vec![], "Something failed" ); ``` -------------------------------- ### Wrap different SourceCode types Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/named-source.md Examples of wrapping various types that implement SourceCode. ```rust use miette::{NamedSource, SourceCode}; // Wrapping a String (most common) let named = NamedSource::new("file.txt", "content".to_string()); // Wrapping a &str reference (if it implements SourceCode) let code = "let x = 5;"; let named = NamedSource::new("inline.rs", code); ``` -------------------------------- ### Create a new MietteDiagnostic Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/miette-diagnostic.md Example of initializing a diagnostic with a simple message. ```rust use miette::MietteDiagnostic; let diag = MietteDiagnostic::new("Something went wrong"); assert_eq!(diag.message, "Something went wrong"); ``` -------------------------------- ### Convert Types to SourceSpan Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/source-code-traits.md Examples of creating SourceSpan instances from tuples, ranges, and explicit constructor calls. ```rust // From tuple let span: SourceSpan = (5, 10).into(); // offset 5, length 10 // From range let span: SourceSpan = (5..15).into(); // offset 5 to 15 // From range inclusive let span: SourceSpan = (5..=15).into(); // offset 5 to 16 // From SourceOffset and usize let span = SourceSpan::new(SourceOffset(5), 10); ``` -------------------------------- ### Creating Dynamic Diagnostics Source: https://github.com/zkat/miette/blob/main/_autodocs/macros.md Examples of using miette macros to generate runtime diagnostics, including formatting, diagnostic codes, and control flow macros like ensure! and bail!. ```rust use miette::{miette, diagnostic, bail, ensure, Result, Severity}; fn main() -> Result<()> { // Create error with message let err1 = miette!("Parse failed"); // Create with formatting let name = "file.txt"; let err2 = miette!("File '{}' not found", name); // Create diagnostic (not wrapped in Report) let diag = diagnostic!( code = "E001", help = "Check file path", "File error" ); // Quick validation with ensure ensure!(5 > 0, "Number must be positive"); // Early return with bail if !condition { bail!("Condition failed"); } Ok(()) } ``` -------------------------------- ### Define InstallError Struct Source: https://github.com/zkat/miette/blob/main/_autodocs/types.md Returned when set_hook fails due to a pre-existing hook installation. ```rust pub struct InstallError; ``` -------------------------------- ### Install miette via Cargo Source: https://github.com/zkat/miette/blob/main/README.md Add the miette dependency to your Rust project. ```shell $ cargo add miette ``` ```shell $ cargo add miette --features fancy ``` -------------------------------- ### Create LabeledSpan with at Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/source-code-traits.md Example usage of the at constructor to create a labeled span. ```rust use miette::LabeledSpan; let span = LabeledSpan::at(5..10, "This is wrong"); ``` -------------------------------- ### Use wrap_err Example Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/wrap-err-trait.md Attaching a context message to a file read operation. ```rust use miette::{IntoDiagnostic, Result, WrapErr}; fn read_config(path: &str) -> Result { std::fs::read_to_string(path) .into_diagnostic() .wrap_err(format!("Failed to read config from {}", path)) } fn main() -> Result<()> { read_config("missing.toml")?; Ok(()) } ``` -------------------------------- ### Common Validation Patterns with ensure! Source: https://github.com/zkat/miette/blob/main/_autodocs/macros.md Example of chaining multiple validation checks using the ensure! macro. ```rust use miette::{ensure, Result}; fn process(input: &str) -> Result<()> { ensure!(!input.is_empty(), "Input cannot be empty"); ensure!(input.len() < 1000, "Input too long"); ensure!(input.chars().all(|c| c.is_ascii()), "Non-ASCII characters"); Ok(()) } ``` -------------------------------- ### Use with_context Example Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/wrap-err-trait.md Attaching a lazily computed context message to a lookup operation. ```rust use miette::{IntoDiagnostic, Result, WrapErr}; use std::collections::HashMap; fn lookup_key(key: &str) -> Result { let map: HashMap<&str, &str> = Default::default(); map.get(key) .copied() .map(|v| v.to_string()) .ok_or_else(|| miette::miette!("Key not found")) .with_context(|| format!("Looking up key '{}'", key)) } ``` -------------------------------- ### Install Global Error Handler Source: https://github.com/zkat/miette/blob/main/_autodocs/configuration.md Configures the global diagnostic rendering hook. Note that this can only be set once per program execution. ```rust use miette::set_hook; let result = set_hook(Box::new(|diagnostic| { Box::new(miette::MietteHandlerOpts::new().build()) })); match result { Ok(()) => println!("Handler installed"), Err(_) => println!("Hook already installed (can only set once)"), } ``` ```rust use miette::{set_hook, MietteHandlerOpts}; fn main() -> miette::Result<()> { // Configure at startup set_hook(Box::new(|_| { Box::new(MietteHandlerOpts::new() .unicode(true) .context_lines(3) .build()) })).ok(); // Ignore if already set // Rest of application Ok(()) } ``` -------------------------------- ### Convert File IO Errors Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/into-diagnostic-trait.md Example of converting std::io::Error into a miette diagnostic. ```rust use miette::{IntoDiagnostic, Result}; use std::io; fn read_file(path: &str) -> Result { std::fs::read_to_string(path).into_diagnostic() } fn main() -> Result<()> { let content = read_file("config.toml")?; println!("{}", content); Ok(()) } ``` -------------------------------- ### Get NamedSource name Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/named-source.md Retrieve the name associated with the source. ```rust pub fn name(&self) -> &str ``` ```rust use miette::NamedSource; let named = NamedSource::new("config.toml", "key = \"value\""); assert_eq!(named.name(), "config.toml"); ``` -------------------------------- ### Initialize Application with Miette Source: https://github.com/zkat/miette/blob/main/_autodocs/README.md Standard boilerplate for using miette::Result in a main function. ```rust use miette::Result; fn main() -> Result<()> { // Your code here Ok(()) } ``` -------------------------------- ### Get inner SourceCode Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/named-source.md Access the underlying source code implementation. ```rust pub fn inner(&self) -> &S ``` ```rust use miette::NamedSource; let source = "code here".to_string(); let named = NamedSource::new("file.rs", source.clone()); assert_eq!(named.inner(), &source); ``` -------------------------------- ### Implement the url method Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/diagnostic-trait.md Provides a URL for further documentation. ```rust fn url<'a>(&'a self) -> Option> ``` ```rust use miette::Diagnostic; use std::error::Error; struct AuthError; impl Error for AuthError {} impl Diagnostic for AuthError { fn url<'a>(&'a self) -> Option> { Some(Box::new("https://example.com/docs/auth-errors")) } } ``` -------------------------------- ### Initialize MietteHandlerOpts Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/miette-handler-opts.md Create a new instance of the options builder using default settings. ```rust use miette::MietteHandlerOpts; let opts = MietteHandlerOpts::new(); ``` -------------------------------- ### Initialize ThemeStyles Source: https://github.com/zkat/miette/blob/main/_autodocs/configuration.md Initialize default diagnostic element colors for further customization. ```rust use miette::ThemeStyles; let styles = ThemeStyles::default(); // Customize styles as needed ``` -------------------------------- ### Trigger InaccessibleSpan Source: https://github.com/zkat/miette/blob/main/_autodocs/errors.md Example of a custom SourceCode implementation that returns an InaccessibleSpan error. ```rust // With a custom SourceCode that fails impl SourceCode for MySource { fn read_span(&self, span: &SourceSpan, ...) -> Result<...> { // If reading fails, InaccessibleSpan is returned Err(MietteError::InaccessibleSpan { span: *span }) } } ``` -------------------------------- ### Implement the help method Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/diagnostic-trait.md Provides additional advice for resolving the error. ```rust fn help<'a>(&'a self) -> Option> ``` ```rust use miette::Diagnostic; use std::error::Error; struct FileNotFound; impl Error for FileNotFound {} impl Diagnostic for FileNotFound { fn help<'a>(&'a self) -> Option> { Some(Box::new("Check that the file path is correct and the file exists")) } } ``` -------------------------------- ### Configure MietteHandlerOpts Source: https://github.com/zkat/miette/blob/main/_autodocs/configuration.md Demonstrates the builder pattern for customizing graphical output, including color, wrapping, and source code display settings. ```rust use miette::{MietteHandlerOpts, RgbColors}; let handler = MietteHandlerOpts::new() // Output formatting .unicode(true) // Use Unicode box-drawing .width(100) // Line width in chars .wrap_lines(true) // Wrap long lines .break_words(true) // Break long words .tab_width(4) // Tab width in spaces // Color configuration .color(true) // Enable colors .rgb_colors(RgbColors::Preferred) // Use RGB if available // Source code display .context_lines(3) // Lines before/after error // Error linking .terminal_links(true) // Clickable error codes // Error chain display .with_cause_chain() // Include cause chain .show_related_errors_as_nested() // Related errors as nested // Footer message .footer("See documentation at docs.example.com".to_string()) // Display mode .force_graphical(false) // Force graphical (overrides detection) .force_narrated(false) // Force text-only (overrides detection) // Syntax highlighting .without_syntax_highlighting() // Disable syntax highlighting .build(); ``` -------------------------------- ### Production Environment Configuration Source: https://github.com/zkat/miette/blob/main/_autodocs/configuration.md Configure the hook for production-ready output with RGB colors and custom footers. ```rust use miette::{set_hook, MietteHandlerOpts, RgbColors}; fn main() -> miette::Result<()> { set_hook(Box::new(|_| { Box::new(MietteHandlerOpts::new() .unicode(true) .width(80) .context_lines(2) .rgb_colors(RgbColors::Preferred) .without_cause_chain() .footer("For support: support@example.com".to_string()) .build()) })).ok(); // Application code Ok(()) } ``` -------------------------------- ### Configure Full MietteHandler Options Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/miette-handler-opts.md Demonstrates a comprehensive configuration of the handler, including terminal links, RGB colors, and custom footer text. ```rust use miette::{MietteHandlerOpts, RgbColors, set_hook}; set_hook(Box::new(|_| { Box::new( MietteHandlerOpts::new() .unicode(true) .context_lines(3) .tab_width(2) .color(true) .rgb_colors(RgbColors::Preferred) .terminal_links(true) .width(100) .wrap_lines(true) .break_words(true) .with_cause_chain() .footer("For more help, visit our documentation".to_string()) .build() ) })).ok(); ``` -------------------------------- ### Trigger SourceIndexOutOfBounds Source: https://github.com/zkat/miette/blob/main/_autodocs/errors.md Example of creating a span that exceeds the source length, triggering a SourceIndexOutOfBounds error. ```rust use miette::{SourceCode, SourceSpan, MietteError}; let source = "hello"; // 5 bytes let span = SourceSpan::new(3.into(), 10); // Asks for 10 bytes starting at offset 3 // This span is invalid for a 5-byte source // Reading it would return MietteError::SourceIndexOutOfBounds ``` -------------------------------- ### MietteHandlerOpts::new Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/miette-handler-opts.md Creates a new instance of the MietteHandlerOpts builder with default configuration values. ```APIDOC ## MietteHandlerOpts::new ### Description Creates a new options builder with all default settings for configuring miette diagnostic handlers. ### Signature `pub fn new() -> Self` ### Returns - **MietteHandlerOpts** - A new builder instance. ### Example ```rust use miette::MietteHandlerOpts; let opts = MietteHandlerOpts::new(); ``` ``` -------------------------------- ### SourceSpan::new Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/source-code-traits.md Creates a new SourceSpan with a specified offset and length. ```APIDOC ## SourceSpan::new ### Description Creates a new SourceSpan instance. ### Signature `pub const fn new(offset: SourceOffset, len: usize) -> Self` ### Parameters - **offset** (SourceOffset) - Required - Starting byte offset - **len** (usize) - Required - Length in bytes ### Returns - **SourceSpan** ``` -------------------------------- ### Integrate with anyhow Source: https://github.com/zkat/miette/blob/main/_autodocs/README.md Use miette::Result as a drop-in replacement for anyhow::Result. ```rust use miette::Result; fn works_with_anyhow() -> Result<()> { std::fs::read_to_string("file.txt") .map_err(|e| miette::miette!("{}", e))?; Ok(()) } ``` -------------------------------- ### Minimal Miette Configuration Source: https://github.com/zkat/miette/blob/main/_autodocs/configuration.md Use the default handler settings for library-friendly output. ```rust use miette::MietteHandlerOpts; let handler = MietteHandlerOpts::new().build(); ``` -------------------------------- ### Disable Colors via Environment Variables Source: https://github.com/zkat/miette/blob/main/_autodocs/configuration.md Examples of setting environment variables to control terminal color output. ```bash NO_COLOR=1 cargo run ``` ```bash CLICOLOR=0 cargo run ``` -------------------------------- ### Screen Reader Friendly Configuration Source: https://github.com/zkat/miette/blob/main/_autodocs/configuration.md Disable color and enable narration mode for improved accessibility. ```rust use miette::{set_hook, MietteHandlerOpts}; fn main() -> miette::Result<()> { set_hook(Box::new(|_| { Box::new(MietteHandlerOpts::new() .force_narrated(true) .color(false) .build()) })).ok(); // Application code Ok(()) } ``` -------------------------------- ### Development Environment Configuration Source: https://github.com/zkat/miette/blob/main/_autodocs/configuration.md Configure the hook for rich, interactive diagnostic output during development. ```rust use miette::{set_hook, MietteHandlerOpts}; fn main() -> miette::Result<()> { set_hook(Box::new(|_| { Box::new(MietteHandlerOpts::new() .unicode(true) .context_lines(5) .color(true) .terminal_links(true) .with_cause_chain() .build()) })).ok(); // Application code Ok(()) } ``` -------------------------------- ### Implement a Custom ReportHandler Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/report-handler.md Defines a custom handler by implementing the ReportHandler trait. This example serializes error details into JSON format. ```rust use miette::{Diagnostic, ReportHandler}; use std::fmt; use std::error::Error; pub struct JSONHandler; impl ReportHandler for JSONHandler { fn debug( &self, error: &dyn Diagnostic, f: &mut fmt::Formatter<'_>, ) -> fmt::Result { let json = serde_json::json!({ "error": error.to_string(), "code": error.code().map(|c| c.to_string()), "severity": format!("{:?}", error.severity()), }); write!(f, "{}", json) } } // Use it fn main() -> miette::Result<()> { miette::set_hook(Box::new(|_| { Box::new(JSONHandler) })).ok(); // Your code here Ok(()) } ``` -------------------------------- ### Register a Global Error Handler Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/report-handler.md Uses set_hook to register a factory that generates a handler for each error. Returns an error if a hook is already installed. ```rust use miette::set_hook; let result = set_hook(Box::new(|_err| { // This closure is called for each error // and should return a handler Box::new(miette::MietteHandlerOpts::new() .unicode(true) .build()) })); match result { Ok(()) => println!("Hook installed"), Err(_) => println!("Hook already installed"), } ``` -------------------------------- ### with_help Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/miette-diagnostic.md Sets the help message for the diagnostic. ```APIDOC ## pub fn with_help(mut self, help: impl Into) -> Self ### Description Set the help message. ### Parameters - **help** (impl Into) - Required - Help text ### Returns MietteDiagnostic ``` -------------------------------- ### Create Report from message Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/report-type.md Instantiate a Report using a simple string message. ```rust use miette::Report; let report = Report::msg("Database connection failed"); ``` -------------------------------- ### Trigger InstallError Source: https://github.com/zkat/miette/blob/main/_autodocs/errors.md Demonstrates how calling set_hook multiple times results in an InstallError. ```rust use miette::{set_hook, MietteHandlerOpts, InstallError}; fn main() -> Result<(), InstallError> { // First call succeeds set_hook(Box::new(|_| { Box::new(MietteHandlerOpts::new().build()) }))?; // Second call fails with InstallError set_hook(Box::new(|_| { Box::new(MietteHandlerOpts::new().build()) }))?; // Returns Err(InstallError) Ok(()) } ``` -------------------------------- ### Handle InstallError Source: https://github.com/zkat/miette/blob/main/_autodocs/errors.md Common patterns for handling the InstallError when configuring the global error hook. ```rust set_hook(Box::new(|_| { Box::new(MietteHandlerOpts::new().build()) })).ok(); // Ignore error if already set ``` ```rust match set_hook(Box::new(|_| { Box::new(MietteHandlerOpts::new().build()) })) { Ok(()) => println!("Error handler configured"), Err(_) => eprintln!("Error handler already configured"), } ``` ```rust set_hook(Box::new(|_| { Box::new(MietteHandlerOpts::new().build()) }))?; ``` -------------------------------- ### with_url Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/miette-diagnostic.md Sets the documentation URL for the diagnostic. ```APIDOC ## pub fn with_url(mut self, url: impl Into) -> Self ### Description Set the documentation URL. ### Parameters - **url** (impl Into) - Required - Documentation URL ### Returns MietteDiagnostic ``` -------------------------------- ### Use diagnostic! Macro Source: https://github.com/zkat/miette/blob/main/_autodocs/macros.md Create a MietteDiagnostic directly instead of wrapping it in a Report. ```rust use miette::diagnostic; let diag = diagnostic!("Something went wrong"); let diag = diagnostic!( code = "E001", help = "Check the input", "Parse error" ); ``` -------------------------------- ### MietteHandlerOpts::build Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/miette-handler-opts.md Consumes the configuration options and returns a concrete implementation of ReportHandler. ```APIDOC ## fn build ### Description Builds the configured handler. This consumes the options and returns a handler ready to use. ### Signature `pub fn build(self) -> impl ReportHandler` ### Parameters - **self** (Self) - Required - The configuration options instance. ### Returns - **impl ReportHandler** - A handler configured according to the specified options. ``` -------------------------------- ### Using WrapErr with miette Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/wrap-err-trait.md Demonstrates using WrapErr to add context to a file read operation. ```rust // Works with both anyhow and miette use miette::{Result, WrapErr}; fn my_function() -> Result<()> { std::fs::read_to_string("file.txt") .into_diagnostic() .wrap_err("Failed to read file")?; Ok(()) } ``` -------------------------------- ### NamedSource::new Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/named-source.md Creates a new instance of NamedSource with a specified name and source code. ```APIDOC ## NamedSource::new ### Description Creates a new NamedSource instance, associating a file name or identifier with the provided source code. ### Parameters - **name** (impl AsRef) - Required - File name or source identifier. - **source** (S) - Required - Source code implementing the SourceCode trait. ### Returns - **NamedSource** - A new instance of NamedSource. ``` -------------------------------- ### Configure Color Options in Rust Source: https://github.com/zkat/miette/blob/main/_autodocs/configuration.md Sets color output preferences and RGB support levels. ```rust use miette::{MietteHandlerOpts, RgbColors}; let handler = MietteHandlerOpts::new() .color(true) // Force colors on .rgb_colors(RgbColors::Preferred) // Use RGB if available .build(); // Or disable colors entirely let handler = MietteHandlerOpts::new() .color(false) .build(); ``` -------------------------------- ### Implement the source_code method Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/diagnostic-trait.md Returns the source code associated with the diagnostic. ```rust fn source_code(&self) -> Option<&dyn SourceCode> ``` ```rust use miette::{Diagnostic, SourceCode}; use std::error::Error; struct SyntaxError { source: String, } impl Error for SyntaxError {} impl Diagnostic for SyntaxError { fn source_code(&self) -> Option<&dyn SourceCode> { Some(&self.source) } } ``` -------------------------------- ### Construct SourceSpan Instances Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/source-code-traits.md Methods for creating new SourceSpan instances with specific offsets and lengths. ```rust pub const fn new(offset: SourceOffset, len: usize) -> Self ``` ```rust pub const fn at_offset(offset: SourceOffset) -> Self ``` -------------------------------- ### Configure ThemeCharacters Source: https://github.com/zkat/miette/blob/main/_autodocs/configuration.md Select between ASCII and Unicode box-drawing characters for diagnostic output. ```rust use miette::ThemeCharacters; // ASCII version let ascii = ThemeCharacters::ascii(); // Unicode version (default) let unicode = ThemeCharacters::unicode(); ``` -------------------------------- ### Create a complete MietteDiagnostic Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/miette-diagnostic.md Constructs a diagnostic with code, severity, help text, URL, and source labels. ```rust use miette::{MietteDiagnostic, LabeledSpan, Severity, Report}; fn main() { let source_code = "let x = 5;".to_string(); let diag = MietteDiagnostic::new("Invalid variable assignment") .with_code("my_app::invalid_assign") .with_severity(Severity::Error) .with_help("Variable names must start with a letter") .with_url("https://docs.example.com/errors#invalid_assign") .with_label(LabeledSpan::at(7..8, "Invalid character")) .with_source_code(source_code); let report: Report = diag.into(); println!("{:?}", report); } ``` -------------------------------- ### Construct MietteSpanContents instances Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/source-code-traits.md Use these constructors to initialize the struct with or without an associated name. ```rust pub const fn new( data: &'a [u8], span: SourceSpan, line: usize, column: usize, line_count: usize, ) -> MietteSpanContents<'a> ``` ```rust pub const fn new_named( name: String, data: &'a [u8], span: SourceSpan, line: usize, column: usize, line_count: usize, ) -> MietteSpanContents<'a> ``` -------------------------------- ### Implement display method Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/report-handler.md Custom implementation of the display method for formatting errors. ```rust use miette::{Diagnostic, ReportHandler}; use std::error::Error; use std::fmt; pub struct SimpleHandler; impl ReportHandler for SimpleHandler { fn debug(&self, error: &dyn Diagnostic, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", error) } fn display( &self, error: &(dyn Error + 'static), f: &mut fmt::Formatter<'_>, ) -> fmt::Result { write!(f, "Error occurred: {}", error) } } ``` -------------------------------- ### Basic Usage of miette! Source: https://github.com/zkat/miette/blob/main/_autodocs/macros.md Create a simple error report with a static message. ```rust use miette::{miette, Result}; fn main() -> Result<()> { Err(miette!("Something went wrong")) } ``` -------------------------------- ### Display Miette Reports in Different Formats Source: https://github.com/zkat/miette/blob/main/_autodocs/errors.md Demonstrates how to use Debug, Display, and Alternate formatting traits to control the verbosity of error output. ```rust use miette::Report; let report = Report::msg("Something failed"); println!("{:?}", report); // Rich diagnostic output ``` ```rust use miette::Report; let report = Report::msg("Something failed"); println!("{}", report); // Simple message ``` ```rust use miette::Report; let report = Report::msg("Something failed"); println!("{:#?}", report); // Include cause chain ``` -------------------------------- ### Replacing anyhow with miette Source: https://github.com/zkat/miette/blob/main/_autodocs/macros.md Demonstrates the drop-in replacement of anyhow! with miette! for basic error creation. ```rust // anyhow style use anyhow::{anyhow, Result}; fn foo() -> Result<()> { Err(anyhow!("Failed: {}", err)) } // miette style (drop-in replacement) use miette::{miette, Result}; fn foo() -> Result<()> { Err(miette!("Failed: {}", err)) } ``` -------------------------------- ### Display project documentation structure Source: https://github.com/zkat/miette/blob/main/_autodocs/MANIFEST.md Visual representation of the documentation file hierarchy for the miette library. ```text output/ ├── INDEX.md # Navigation index (START HERE) ├── README.md # Project overview ├── types.md # Type catalog ├── macros.md # Macro reference ├── configuration.md # Configuration guide ├── errors.md # Error handling guide └── api-reference/ ├── diagnostic-trait.md # Diagnostic trait API ├── report-type.md # Report struct API ├── report-handler.md # ReportHandler trait API ├── source-code-traits.md # Source code types API ├── named-source.md # NamedSource struct API ├── miette-diagnostic.md # MietteDiagnostic struct API ├── miette-handler-opts.md # Handler configuration builder API ├── into-diagnostic-trait.md # IntoDiagnostic trait API └── wrap-err-trait.md # WrapErr trait API ``` -------------------------------- ### Configure Miette Handler for Environment Source: https://github.com/zkat/miette/blob/main/_autodocs/configuration.md Initializes a Miette handler with dynamic detection of unicode and color support based on the standard output stream. ```rust use miette::MietteHandlerOpts; let handler = MietteHandlerOpts::new() .unicode(supports_unicode::on(supports_unicode::Stream::Stdout)) .color(supports_color::on(supports_color::Stream::Stdout).is_some()) .build(); ``` -------------------------------- ### Configure Display Options in Rust Source: https://github.com/zkat/miette/blob/main/_autodocs/configuration.md Adjusts output formatting such as Unicode usage, line width, and word wrapping. ```rust use miette::MietteHandlerOpts; let handler = MietteHandlerOpts::new() .unicode(false) // Use ASCII art instead of Unicode .width(120) // Wider output .tab_width(2) // Narrower tabs .wrap_lines(false) // Don't wrap lines .break_words(false) // Don't break words .build(); ``` -------------------------------- ### Converting Types to Report Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/report-type.md Demonstrates converting diagnostics, Strings, and string slices into a Report. ```rust // From any Diagnostic + Send + Sync + 'static let report: Report = my_diagnostic.into(); // From String let report: Report = "Error message".to_string().into(); // From &str let report: Report = "Error message".into(); ``` -------------------------------- ### Compare Error Handling Approaches Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/into-diagnostic-trait.md Comparison between using IntoDiagnostic and manual mapping. ```rust use miette::{IntoDiagnostic, Result}; fn main() -> Result<()> { let num: i32 = "42".parse().into_diagnostic()?; Ok(()) ``` ```rust use miette::{Report, Result}; fn main() -> Result<()> { let num: i32 = "42" .parse() .map_err(|e| Report::msg(format!("Parse failed: {}", e)))?; Ok(()) ``` -------------------------------- ### Set diagnostic documentation URL Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/miette-diagnostic.md Attach a URL for further documentation regarding the error. ```rust use miette::MietteDiagnostic; let diag = MietteDiagnostic::new("Auth failed") .with_url("https://docs.example.com/auth"); ``` -------------------------------- ### Wrap Option types with WrapErr Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/wrap-err-trait.md Shows how to convert an Option into a Result with context when a value is missing. ```rust use miette::{Result, WrapErr}; fn get_env(key: &str) -> Result { std::env::var(key) .ok() .wrap_err(format!("Environment variable '{}' not found", key)) } fn main() -> Result<()> { let api_key = get_env("API_KEY")?; println!("API Key: {}", api_key); Ok(()) } ``` -------------------------------- ### with_labels Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/miette-diagnostic.md Sets multiple labels, replacing any previous labels. ```APIDOC ## pub fn with_labels(mut self, labels: impl IntoIterator) -> Self ### Description Set multiple labels, replacing any previous labels. ### Parameters - **labels** (impl IntoIterator) - Required - Collection of labels ### Returns MietteDiagnostic ``` -------------------------------- ### Handle diagnostics in main Source: https://github.com/zkat/miette/blob/main/README.md Return a Result from main to enable automatic pretty-printing of diagnostics. ```rust 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(()) } ``` -------------------------------- ### Returning Report from Main Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/report-type.md Using Result in main allows miette to automatically format and display errors. ```rust use miette::Result; fn main() -> Result<()> { let data = std::fs::read_to_string("config.toml")?; // ... process data ... Ok(()) } ``` -------------------------------- ### Constructor definition Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/miette-handler-opts.md The signature for the new constructor method. ```rust pub fn new() -> Self ``` -------------------------------- ### Implement SourceCode trait Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/named-source.md Demonstrates delegation to the inner source code. ```rust use miette::{NamedSource, SourceCode, SourceSpan}; let source = NamedSource::new( "example.rs", "fn main() {\n let x = 5;\n}".to_string() ); let span = SourceSpan::new((0).into(), 4); let contents = source.read_span(&span, 0, 0).unwrap(); assert_eq!(contents.name(), Some("example.rs")); ``` -------------------------------- ### Create dynamic diagnostics with miette! Source: https://github.com/zkat/miette/blob/main/README.md Use the miette! macro to generate diagnostics on the fly when error structures are not known upfront. ```rust let source = "2 + 2 * 2 = 8".to_string(); let report = miette!( labels = vec![ LabeledSpan::at(12..13, "this should be 6"), ], help = "'*' has greater precedence than '+'", "Wrong answer" ).with_source_code(source); println!("{:?}", report) ``` -------------------------------- ### Implement the severity method Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/diagnostic-trait.md Sets the diagnostic severity level. ```rust fn severity(&self) -> Option ``` ```rust use miette::{Diagnostic, Severity}; use std::error::Error; struct WarningError; impl Error for WarningError {} impl Diagnostic for WarningError { fn severity(&self) -> Option { Some(Severity::Warning) } } ``` -------------------------------- ### Deriving Diagnostic and Using miette! Macro Source: https://github.com/zkat/miette/blob/main/_autodocs/macros.md Demonstrates the distinction between using the derive macro for library code and the miette! macro for application-level error handling. ```rust // Library code - use derive use miette::{Diagnostic, SourceSpan}; use thiserror::Error; #[derive(Error, Diagnostic, Debug)] #[error("Parse error")] #[diagnostic(code(my_lib::parse_error))] pub struct ParseError { #[source_code] src: String, #[label("Here")] span: SourceSpan, } // Application code - use macros use miette::{miette, Result}; fn main() -> Result<()> { Err(miette!("Something failed")) } ``` -------------------------------- ### Configure Miette Feature Flags Source: https://github.com/zkat/miette/blob/main/_autodocs/configuration.md Cargo dependency configurations for enabling specific Miette features. ```toml [dependencies] miette = { version = "7.6", features = ["fancy"] } ``` ```toml [dependencies] miette = { version = "7.6", features = ["fancy-no-backtrace"] } ``` ```toml [dependencies] miette = { version = "7.6", features = ["fancy-no-syscall"] } ``` ```toml [dependencies] miette = { version = "7.6", features = ["fancy", "syntect-highlighter"] } ``` ```toml [dependencies] miette = { version = "7.6", features = ["serde"] } ``` ```toml [dependencies] miette = { version = "7.6", features = ["derive"] } ``` -------------------------------- ### SourceCode Trait Hierarchy Source: https://github.com/zkat/miette/blob/main/_autodocs/types.md Illustrates how source code types are wrapped and implemented. ```text SourceCode (trait) ↓ NamedSource (wraps S: SourceCode) ↓ String, &str, custom types ``` -------------------------------- ### CI/CD Environment Configuration Source: https://github.com/zkat/miette/blob/main/_autodocs/configuration.md Configure the hook for log-friendly output by disabling ANSI colors and Unicode characters. ```rust use miette::{set_hook, MietteHandlerOpts}; fn main() -> miette::Result<()> { set_hook(Box::new(|_| { Box::new(MietteHandlerOpts::new() .unicode(false) // ASCII for log parsing .color(false) // No ANSI codes in logs .width(120) // Wider output .context_lines(3) .with_cause_chain() .build()) })).ok(); // Application code Ok(()) } ``` -------------------------------- ### with_label Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/miette-diagnostic.md Sets a single label, replacing any previous labels. ```APIDOC ## pub fn with_label(mut self, label: impl Into) -> Self ### Description Set a single label, replacing any previous labels. ### Parameters - **label** (impl Into) - Required - A labeled span ### Returns MietteDiagnostic ``` -------------------------------- ### Using Nested Format Arguments in miette! Source: https://github.com/zkat/miette/blob/main/_autodocs/macros.md Illustrates how to pass formatted strings into the miette! macro. ```rust use miette::{miette, Result}; fn process(count: i32) -> Result<()> { let msg = format!("Processed {} items", count); Err(miette!("Operation failed: {}", msg)) } ``` -------------------------------- ### Create a Simple Error Source: https://github.com/zkat/miette/blob/main/_autodocs/INDEX.md Use the miette macro to generate a basic diagnostic error. ```rust use miette::miette; Err(miette!("Something failed")) ``` -------------------------------- ### MietteSpanContents::new_named Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/source-code-traits.md Creates a new instance of MietteSpanContents with an associated file or source name. ```APIDOC ## MietteSpanContents::new_named ### Description Creates a new instance of MietteSpanContents with an associated file or source name. ### Parameters - **name** (String) - Required - File or source name - **data** (&'a [u8]) - Required - Source code bytes - **span** (SourceSpan) - Required - The span - **line** (usize) - Required - 0-indexed starting line - **column** (usize) - Required - 0-indexed starting column - **line_count** (usize) - Required - Number of lines ### Returns - **MietteSpanContents<'a>** - A new instance of the struct. ``` -------------------------------- ### Set language for syntax highlighting Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/named-source.md Configure the language identifier for the source. ```rust pub fn with_language(mut self, language: impl Into) -> Self ``` ```rust use miette::NamedSource; let named = NamedSource::new("script.py", "print('hello')") .with_language("Python"); ``` -------------------------------- ### Handling Empty Labels in miette! Source: https://github.com/zkat/miette/blob/main/_autodocs/macros.md Shows that labels can be initialized as an empty vector within the miette! macro. ```rust use miette::miette; // Valid - labels can be empty let err = miette!( labels = vec![], "Error message" ); ``` -------------------------------- ### MietteSpanContents::new Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/source-code-traits.md Creates a new instance of MietteSpanContents with the required source data and span information. ```APIDOC ## MietteSpanContents::new ### Description Creates a new instance of MietteSpanContents with the required source data and span information. ### Parameters - **data** (&'a [u8]) - Required - Source code bytes - **span** (SourceSpan) - Required - The span - **line** (usize) - Required - 0-indexed starting line - **column** (usize) - Required - 0-indexed starting column - **line_count** (usize) - Required - Number of lines ### Returns - **MietteSpanContents<'a>** - A new instance of the struct. ``` -------------------------------- ### Configure syntax highlighting in Rust Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/miette-handler-opts.md Enable syntax highlighting using a custom implementation or explicitly disable it. ```rust use miette::MietteHandlerOpts; let opts = MietteHandlerOpts::new() .with_syntax_highlighting(my_custom_highlighter); ``` ```rust use miette::MietteHandlerOpts; let opts = MietteHandlerOpts::new() .without_syntax_highlighting(); ``` -------------------------------- ### Use bail! Macro with Parameters Source: https://github.com/zkat/miette/blob/main/_autodocs/macros.md Provide additional diagnostic details when using the bail! macro. ```rust use miette::{bail, Severity}; fn validate() -> miette::Result<()> { bail!( code = "validation::failed", severity = Severity::Error, help = "Check input constraints", "Validation failed" ) } ``` -------------------------------- ### Link to docs.rs diagnostics Source: https://github.com/zkat/miette/blob/main/README.md Use the url(docsrs) option to automatically link to documentation on docs.rs. ```rust 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; ``` -------------------------------- ### Configure Unicode usage Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/miette-handler-opts.md Toggle between Unicode box-drawing characters and ASCII art. ```rust use miette::MietteHandlerOpts; let opts = MietteHandlerOpts::new() .unicode(true); // Use Unicode boxes ``` -------------------------------- ### Attaching Source Code to Diagnostics Source: https://github.com/zkat/miette/blob/main/_autodocs/macros.md Shows how to associate source code and labeled spans with errors using the miette macro. ```rust use miette::{miette, Result, NamedSource, LabeledSpan}; fn main() -> Result<()> { let source = "let x = 42;".to_string(); let named = NamedSource::new("script.rs", source); Err(miette!( labels = vec![LabeledSpan::at(7..9, "error")], help = "Check syntax", "Parse error" ).with_source_code(named)) } ``` -------------------------------- ### Combine with WrapErr Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/into-diagnostic-trait.md Adding context to errors while converting them. ```rust use miette::{IntoDiagnostic, Result, WrapErr}; fn connect_database(url: &str) -> Result<()> { // Some database connection code std::io::Error::new( std::io::ErrorKind::ConnectionRefused, "Connection failed" ) .into_diagnostic() .wrap_err(format!("Failed to connect to {}", url)) } fn main() -> Result<()> { connect_database("postgres://localhost")?; Ok(()) ``` -------------------------------- ### Add Diagnostic Fields to miette! Source: https://github.com/zkat/miette/blob/main/_autodocs/macros.md Include structured diagnostic information such as labels, help text, and error codes. ```rust use miette::{miette, LabeledSpan, Result}; fn main() -> Result<()> { let source = "let x = 42;".to_string(); Err(miette!( labels = vec![LabeledSpan::at(7..9, "error here")], help = "Check the syntax", code = "E001", "Invalid syntax" ).with_source_code(source)) } ``` -------------------------------- ### Define ThemeStyles struct Source: https://github.com/zkat/miette/blob/main/_autodocs/types.md Color and text styling for different diagnostic elements. ```rust pub struct ThemeStyles { pub error: Style, pub warning: Style, pub advice: Style, pub help: Style, pub highlight: Style, } ``` -------------------------------- ### Construct NamedSource Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/named-source.md Signature for creating a new NamedSource instance. ```rust pub fn new(name: impl AsRef, source: S) -> Self where S: Send + Sync, ``` ```rust use miette::NamedSource; let source = "fn main() {}".to_string(); let named = NamedSource::new("main.rs", source); ``` -------------------------------- ### Reporting errors with context in main Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/wrap-err-trait.md Shows how miette displays error chains when returning from main. ```rust use miette::{IntoDiagnostic, Result, WrapErr}; fn main() -> Result<()> { std::fs::read_to_string("missing.txt") .into_diagnostic() .wrap_err("Loading data failed")?; Ok(()) } ``` -------------------------------- ### Format Messages with miette! Source: https://github.com/zkat/miette/blob/main/_autodocs/macros.md Use standard formatting syntax within the error message. ```rust use miette::{miette, Result}; fn main() -> Result<()> { let value = "invalid"; Err(miette!("Invalid value: {}", value)) } ``` -------------------------------- ### Define Diagnostics with Error Codes and Links Source: https://github.com/zkat/miette/blob/main/_autodocs/README.md Use the miette! macro to attach error codes, documentation URLs, and help messages to diagnostics. ```rust use miette::{miette, Result}; fn main() -> Result<()> { Err(miette!( code = "app::auth_failed", url = "https://docs.example.com/errors#auth_failed", help = "Check your credentials", "Authentication failed" )) } ``` -------------------------------- ### Build a MietteHandler Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/miette-handler-opts.md Constructs a report handler using the builder pattern and registers it with the global hook. ```rust use miette::{MietteHandlerOpts, set_hook}; let opts = MietteHandlerOpts::new() .unicode(true) .context_lines(3) .tab_width(4); set_hook(Box::new(|_| { Box::new(opts.clone().build()) })).ok(); ``` -------------------------------- ### MietteHandlerOpts Configuration Methods Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/miette-handler-opts.md Methods available on the MietteHandlerOpts builder to customize error reporting behavior. ```APIDOC ## show_related_errors_as_siblings() ### Description Display related errors at the same level as the main error. ### Signature `pub fn show_related_errors_as_siblings(mut self) -> Self` ## show_related_errors_as_nested() ### Description Display related errors as nested under the main error. ### Signature `pub fn show_related_errors_as_nested(mut self) -> Self` ## color(color: bool) ### Description Whether to use colors during rendering. If unspecified, colors are used only if the terminal supports them. ### Signature `pub fn color(mut self, color: bool) -> Self` ## rgb_colors(color: RgbColors) ### Description Control which color format to use (RGB vs ANSI). Default is RgbColors::Never. Has no effect if colors are disabled. ### Signature `pub fn rgb_colors(mut self, color: RgbColors) -> Self` ## unicode(unicode: bool) ### Description Whether to use Unicode box-drawing characters. If false, uses ASCII art. ### Signature `pub fn unicode(mut self, unicode: bool) -> Self` ## force_graphical(force: bool) ### Description Force graphical rendering regardless of terminal detection. ### Signature `pub fn force_graphical(mut self, force: bool) -> Self` ## force_narrated(force: bool) ### Description Force narrated (text-only) rendering. ### Signature `pub fn force_narrated(mut self, force: bool) -> Self` ## footer(footer: String) ### Description Set a footer to display at the bottom of the report. ### Signature `pub fn footer(mut self, footer: String) -> Self` ## context_lines(context_lines: usize) ### Description Set the number of context lines to show before and after error spans. Defaults to 1. ### Signature `pub fn context_lines(mut self, context_lines: usize) -> Self` ## tab_width(width: usize) ### Description Set the displayed tab width in spaces. Defaults to 4. ### Signature `pub fn tab_width(mut self, width: usize) -> Self` ``` -------------------------------- ### LabeledSpan Constructors Source: https://github.com/zkat/miette/blob/main/_autodocs/api-reference/source-code-traits.md Methods for creating new LabeledSpan instances. ```APIDOC ## LabeledSpan Constructors ### new(label: Option, offset: ByteOffset, len: usize) -> Self Creates a new labeled span with a specific offset and length. ### new_with_span(label: Option, span: impl Into) -> Self Creates a labeled span from an existing SourceSpan. ### new_primary_with_span(label: Option, span: impl Into) -> Self Creates a primary labeled span, typically used to mark the main error location. ### at(span: impl Into, label: impl Into) -> Self Creates a labeled span at a specified location with required label text. ### at_offset(offset: ByteOffset, label: impl Into) -> Self Creates a label pointing at a specific offset with zero length. ### underline(span: impl Into) -> Self Creates a label without text that underlines a specific span. ```