miette/
error.rs

1use std::{fmt, io};
2
3use thiserror::Error;
4
5use crate::Diagnostic;
6
7/**
8Error enum for miette. Used by certain operations in the protocol.
9*/
10#[derive(Debug, Error)]
11pub enum MietteError {
12    /// Wrapper around [`std::io::Error`]. This is returned when something went
13    /// wrong while reading a [`SourceCode`](crate::SourceCode).
14    #[error(transparent)]
15    IoError(#[from] io::Error),
16
17    /// Returned when a [`SourceSpan`](crate::SourceSpan) extends beyond the
18    /// bounds of a given [`SourceCode`](crate::SourceCode).
19    #[error("The given offset is outside the bounds of its Source")]
20    OutOfBounds,
21}
22
23impl Diagnostic for MietteError {
24    fn code<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
25        match self {
26            MietteError::IoError(_) => Some(Box::new("miette::io_error")),
27            MietteError::OutOfBounds => Some(Box::new("miette::span_out_of_bounds")),
28        }
29    }
30
31    fn help<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
32        match self {
33            MietteError::IoError(_) => None,
34            MietteError::OutOfBounds => Some(Box::new(
35                "Double-check your spans. Do you have an off-by-one error?",
36            )),
37        }
38    }
39
40    fn url<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
41        let crate_version = env!("CARGO_PKG_VERSION");
42        let variant = match self {
43            MietteError::IoError(_) => "#variant.IoError",
44            MietteError::OutOfBounds => "#variant.OutOfBounds",
45        };
46        Some(Box::new(format!(
47            "https://docs.rs/miette/{}/miette/enum.MietteError.html{}",
48            crate_version, variant,
49        )))
50    }
51}