Skip to main content

Error

Struct Error 

Source
pub struct Error { /* private fields */ }
Expand description

A single error from parsing or converting a TOML document.

Errors arise from two phases:

  • Parsing: syntax errors such as unterminated strings, duplicate keys, or unexpected characters. parse returns the first such error as Err(Error).

  • Conversion: type mismatches, missing fields, unknown keys, and other constraint violations detected by FromToml. These accumulate so that a single pass surfaces as many problems as possible.

parse_recoverable combines both phases, continuing past syntax errors and collecting them alongside conversion errors into a single Document::errors list.

§Extracting information

MethodReturns
kind()The ErrorKind variant for this error
span()Source Span (byte offsets), 0..0 when no location applies
path()Optional TomlPath to the offending value
message(source)Human-readable diagnostic message
primary_label()Optional (Span, String) label for the error site
secondary_label()Optional (Span, String) for related locations

The message, primary_label, and secondary_label methods provide building blocks for rich diagnostics, mapping onto the label model used by codespan-reporting and annotate-snippets.

§Integration with error reporting libraries

codespan-reporting example
use codespan_reporting::diagnostic::{Diagnostic, Label};

fn error_to_diagnostic(
    error: &toml_spanner::Error,
    source: &str,
) -> Diagnostic<()> {
    let mut labels = Vec::new();
    if let Some((span, text)) = error.secondary_label() {
        labels.push(Label::secondary((), span).with_message(text));
    }
    if let Some((span, label)) = error.primary_label() {
        let l = Label::primary((), span);
        labels.push(if label.is_empty() {
            l
        } else {
            l.with_message(label)
        });
    }
    Diagnostic::error()
        .with_code(error.kind().kind_name())
        .with_message(error.message_with_path(source))
        .with_labels(labels)
}
annotate-snippets example
use annotate_snippets::{AnnotationKind, Group, Level, Snippet};

fn error_to_snippet<'s>(
    error: &toml_spanner::Error,
    source: &'s str,
    path: &'s str,
) -> Group<'s> {
    let message = error.message_with_path(source);
    let mut snippet = Snippet::source(source).path(path).fold(true);
    if let Some((span, text)) = error.secondary_label() {
        snippet = snippet.annotation(
            AnnotationKind::Context.span(span.range()).label(text),
        );
    }
    if let Some((span, label)) = error.primary_label() {
        let ann = AnnotationKind::Primary.span(span.range());
        snippet = snippet.annotation(if label.is_empty() {
            ann
        } else {
            ann.label(label)
        });
    }
    Level::ERROR.primary_title(message).element(snippet)
}

§Multiple error accumulation

During FromToml conversion, errors are pushed into a shared Context rather than causing an immediate abort. The sentinel type Failed signals that a branch failed without carrying error details itself. When Document::to or from_str finishes, all accumulated errors are returned in FromTomlError::errors.

parse_recoverable extends this to the parsing phase, collecting syntax errors into the same list so valid portions of the document remain available for inspection.

Implementations§

Source§

impl Error

Source

pub fn span(&self) -> Span

Returns the source span where this error occurred.

A span of 0..0 (Span::is_empty) means the error has no specific source location, as with ErrorKind::FileTooLarge.

Source

pub fn kind(&self) -> ErrorKind<'_>

Returns the error kind.

Source

pub fn path<'a>(&'a self) -> Option<&'a TomlPath<'a>>

Returns the TOML path where this error occurred, if available.

Source

pub fn custom(message: impl ToString, span: Span) -> Error

Creates an error with a custom message at the given source span.

Source§

impl Error

Source

pub fn message(&self, source: &str) -> String

Returns the diagnostic message for this error, without the TOML path.

Some error kinds extract names from source for richer messages.

Source

pub fn message_with_path(&self, source: &str) -> String

Returns the diagnostic message for this error, with the TOML path appended.

Some error kinds extract names from source for richer messages.

Source

pub fn primary_label(&self) -> Option<(Span, String)>

Returns the primary label span and text for this error, if any.

Source

pub fn secondary_label(&self) -> Option<(Span, String)>

Returns the secondary label span and text, if any.

Some errors reference a related location (for example, the first definition of a duplicate key).

Trait Implementations§

Source§

impl Debug for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for Error

1.30.0 · Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0:

use the Display impl or to_string()

1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<(ErrorKind<'static>, Span)> for Error

Source§

fn from((kind, span): (ErrorKind<'static>, Span)) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for FromTomlError

Available on crate feature from-toml only.
Source§

fn from(error: Error) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl Freeze for Error

§

impl RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl UnsafeUnpin for Error

§

impl UnwindSafe for Error

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.