Skip to main content

Error

Enum Error 

#[non_exhaustive]
pub enum Error {
Show 27 variants Parse(String), ParseWithLocation { message: String, location: Location, }, Serialize(String), Deserialize(String), DeserializeWithLocation { message: String, location: Location, }, Io(Error), Custom(String), RecursionLimitExceeded { depth: usize, }, DuplicateKey(String), RepetitionLimitExceeded, Budget(BudgetBreach), UnknownAnchor(String), UnknownAnchorAt { name: String, location: Location, suggestion: Option<(String, Location)>, }, MissingField(String), UnknownField(String), ScalarInMergeElement, SequenceInMergeElement, TaggedInMerge, Invalid(String), TypeMismatch { expected: &'static str, found: String, }, Shared(Arc<Error>), EndOfStream, MoreThanOneDocument, ScalarInMerge, EmptyTag, FailedToParseNumber(String), Message(String, Option<usize>),
}
Expand description

§Examples

use noyalib::{from_str, Error, Value};
let err = from_str::<Value>("a: [unclosed").unwrap_err();
assert!(matches!(err, Error::Parse(_) | Error::ParseWithLocation { .. }));

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Parse(String)

Error during YAML parsing.

§Examples

let _e = noyalib::Error::Parse("unexpected token".into());
§

ParseWithLocation

Error during YAML parsing with location information.

§Examples

use noyalib::{Error, Location};
let _e = Error::ParseWithLocation {
    message: "bad token".into(),
    location: Location::from_index("a: [", 3),
};

Fields

§message: String

The error message.

§Examples
use noyalib::{Error, Location};
let e = Error::ParseWithLocation {
    message: "bad".into(),
    location: Location::default(),
};
if let Error::ParseWithLocation { message, .. } = e {
    assert_eq!(message, "bad");
}
§location: Location

The location in the source where the error occurred.

§Examples
use noyalib::{Error, Location};
let e = Error::ParseWithLocation {
    message: "x".into(),
    location: Location::from_index("abc", 1),
};
if let Error::ParseWithLocation { location, .. } = e {
    assert_eq!(location.column(), 2);
}
§

Serialize(String)

Error during serialization.

§Examples

let _e = noyalib::Error::Serialize("bad value".into());
§

Deserialize(String)

Error during deserialization.

§Examples

let _e = noyalib::Error::Deserialize("type mismatch".into());
§

DeserializeWithLocation

Error during deserialization with location information.

§Examples

use noyalib::{Error, Location};
let _e = Error::DeserializeWithLocation {
    message: "expected int".into(),
    location: Location::default(),
};

Fields

§message: String

The error message.

§Examples
use noyalib::{Error, Location};
let e = Error::DeserializeWithLocation {
    message: "m".into(),
    location: Location::default(),
};
if let Error::DeserializeWithLocation { message, .. } = e {
    assert_eq!(message, "m");
}
§location: Location

The location in the source where the error occurred.

§Examples
use noyalib::{Error, Location};
let e = Error::DeserializeWithLocation {
    message: "m".into(),
    location: Location::from_index("ab", 1),
};
if let Error::DeserializeWithLocation { location, .. } = e {
    assert_eq!(location.column(), 2);
}
§

Io(Error)

I/O error (requires std feature).

§Examples

let ioe = std::io::Error::new(std::io::ErrorKind::Other, "nope");
let _e = noyalib::Error::Io(ioe);
§

Custom(String)

Custom error message.

§Examples

let _e = noyalib::Error::Custom("whatever".into());
§

RecursionLimitExceeded

Error when recursion depth limit is exceeded.

§Examples

let _e = noyalib::Error::RecursionLimitExceeded { depth: 64 };

Fields

§depth: usize

The current depth.

§Examples
use noyalib::Error;
if let Error::RecursionLimitExceeded { depth } =
    (Error::RecursionLimitExceeded { depth: 10 })
{
    assert_eq!(depth, 10);
}
§

DuplicateKey(String)

Error when a duplicate key is encountered.

§Examples

let _e = noyalib::Error::DuplicateKey("name".into());
§

RepetitionLimitExceeded

Repetition limit exceeded (security limit against billion-laughs).

§Examples

let _e = noyalib::Error::RepetitionLimitExceeded;
§

Budget(BudgetBreach)

A configurable parser budget was exceeded.

Carries a [BudgetBreach] identifying which limit fired, the configured cap, and (where meaningful) the observed value at the moment the cap tripped. Distinct from the older Error::RecursionLimitExceeded / Error::RepetitionLimitExceeded variants — those stay for backwards compatibility on the depth / alias-expansion limits; new budgets in the v0.0.2 expansion (max_events, max_nodes, max_total_scalar_bytes, max_documents, max_merge_keys, alias_anchor_ratio) all flow through Error::Budget.

§Examples

use noyalib::{BudgetBreach, Error};
let _e = Error::Budget(BudgetBreach::MaxDocuments {
    limit: 1_000,
    observed: 1_001,
});
§

UnknownAnchor(String)

Unknown anchor encountered.

§Examples

let _e = noyalib::Error::UnknownAnchor("missing".into());
§

UnknownAnchorAt

Unknown anchor encountered at a specific location.

§Examples

use noyalib::{Error, Location};
let _e = Error::UnknownAnchorAt {
    name: "x".into(),
    location: Location::default(),
    suggestion: None,
};

Fields

§name: String

The anchor name.

§Examples
use noyalib::{Error, Location};
let e = Error::UnknownAnchorAt {
    name: "x".into(),
    location: Location::default(),
    suggestion: None,
};
if let Error::UnknownAnchorAt { name, .. } = e {
    assert_eq!(name, "x");
}
§location: Location

The location where it was used.

§Examples
use noyalib::{Error, Location};
let e = Error::UnknownAnchorAt {
    name: "x".into(),
    location: Location::from_index("ab", 1),
    suggestion: None,
};
if let Error::UnknownAnchorAt { location, .. } = e {
    assert_eq!(location.column(), 2);
}
§suggestion: Option<(String, Location)>

Optional suggestion for a similar anchor.

§Examples
use noyalib::{Error, Location};
let e = Error::UnknownAnchorAt {
    name: "x".into(),
    location: Location::default(),
    suggestion: Some(("y".into(), Location::default())),
};
if let Error::UnknownAnchorAt { suggestion: Some((s, _)), .. } = e {
    assert_eq!(s, "y");
}
§

MissingField(String)

Missing field in a mapping.

§Examples

let _e = noyalib::Error::MissingField("name".into());
§

UnknownField(String)

Unknown field in a mapping (with deny_unknown_fields).

§Examples

let _e = noyalib::Error::UnknownField("extra".into());
§

ScalarInMergeElement

Scalar encountered where a mapping was expected during merge.

§Examples

let _e = noyalib::Error::ScalarInMergeElement;
§

SequenceInMergeElement

Sequence encountered where a mapping was expected during merge.

§Examples

let _e = noyalib::Error::SequenceInMergeElement;
§

TaggedInMerge

Tagged value encountered during merge.

§Examples

let _e = noyalib::Error::TaggedInMerge;
§

Invalid(String)

Generic invalid construct error.

§Examples

let _e = noyalib::Error::Invalid("bad construct".into());
§

TypeMismatch

A type mismatch error.

§Examples

let _e = noyalib::Error::TypeMismatch {
    expected: "integer",
    found: "string".into(),
};

Fields

§expected: &'static str

The expected type.

§Examples
use noyalib::Error;
let e = Error::TypeMismatch { expected: "int", found: "str".into() };
if let Error::TypeMismatch { expected, .. } = e {
    assert_eq!(expected, "int");
}
§found: String

The type that was actually found.

§Examples
use noyalib::Error;
let e = Error::TypeMismatch { expected: "int", found: "str".into() };
if let Error::TypeMismatch { found, .. } = e {
    assert_eq!(found, "str");
}
§

Shared(Arc<Error>)

Shared error instance (Arc-wrapped for cloning).

§Examples

use std::sync::Arc;
let _e = noyalib::Error::Shared(Arc::new(noyalib::Error::EndOfStream));
§

EndOfStream

End of stream reached unexpectedly.

§Examples

let _e = noyalib::Error::EndOfStream;
§

MoreThanOneDocument

More than one document found where one was expected.

§Examples

let _e = noyalib::Error::MoreThanOneDocument;
§

ScalarInMerge

Scalar in merge (legacy variant).

§Examples

let _e = noyalib::Error::ScalarInMerge;
§

EmptyTag

Empty tag encountered.

§Examples

let _e = noyalib::Error::EmptyTag;
§

FailedToParseNumber(String)

Failed to parse a number.

§Examples

let _e = noyalib::Error::FailedToParseNumber("not-a-number".into());
§

Message(String, Option<usize>)

A message error from Serde (compat variant).

§Examples

let _e = noyalib::Error::Message("oops".into(), Some(42));

Implementations§

§

impl Error

pub fn render_with_formatter(&self, formatter: &dyn MessageFormatter) -> String

Render this error via a custom [MessageFormatter].

Pairs with [DefaultFormatter] (developer-facing, verbatim) and [UserFormatter] (user-facing, simplified). Callers needing localisation or rich formatting plug in their own MessageFormatter impl.

§Examples
use noyalib::i18n::UserFormatter;
use noyalib::{from_str, Value};

let err = from_str::<Value>("a: [unclosed").unwrap_err();
let msg = err.render_with_formatter(&UserFormatter);
assert!(msg.contains("syntax error"));
§

impl Error

pub fn location(&self) -> Option<Location>

Get the location of the error, if any.

§Examples
use noyalib::{from_str, Value};
let err = from_str::<Value>("a: [unclosed").unwrap_err();
let _ = err.location();

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

Format the error with source context. If the error carries a source location and the line is in range, the output includes a line <n>:<col> prefix, the offending line, and a caret (^) pointing at the column. Out-of-range lines fall back to plain Display.

For rustc-style multi-line context with surrounding lines, use Self::format_with_source_radius.

§Examples
use noyalib::{from_str, Value};
let source = "a: [unclosed";
let err = from_str::<Value>(source).unwrap_err();
let formatted = err.format_with_source(source);
assert!(formatted.contains("error"));

pub fn format_with_source_radius(&self, source: &str, radius: usize) -> String

Format the error with radius lines of context above and below the offending line — rustc-style. Each line gets a line number on the left; the caret line under the offending column is unnumbered. The output is byte-for-byte stable across minor releases (no terminal escape codes, no platform-conditional whitespace).

Out-of-range locations fall back to plain Display (no snippet) — same contract as Self::format_with_source.

§Examples
use noyalib::{from_str, Value};
// Indentation-mismatch error — carries a concrete `(line,
// column)` location, so the snippet renderer engages.
let source = "\
header: ok
service:
   nested: x
  bad: y
trailer: ok
";
let e = from_str::<Value>(source).unwrap_err();
let formatted = e.format_with_source_radius(source, 1);
// Output includes the offending line plus a single line
// of context above and below.
assert!(formatted.contains("|"));
assert!(formatted.contains("bad: y"));

pub fn format_with_source_truncated( &self, source: &str, max_chars: usize, ) -> String

Format the error with source context, capped at max_chars ASCII characters — the bridged-channel-friendly variant of Self::format_with_source. Use when the diagnostic is destined for a Slack message, a Sentry tag, a structured log field, or any sink with a hard length budget.

§Truncation contract
  1. The output is plain ASCII (the renderer already emits no ANSI escapes, so this is a no-op for that axis).
  2. If the rendered string is <= max_chars, returns it unchanged.
  3. Otherwise truncates at a UTF-8 character boundary <= max_chars - 3 and appends an ... ellipsis so the final length is at most max_chars.
  4. max_chars smaller than 3 keeps as much of the prefix as fits and drops the ellipsis (so a max_chars = 2 yields exactly two characters of the message).
§Examples
use noyalib::{from_str, Value};
let source = "a: [unclosed";
let err = from_str::<Value>(source).unwrap_err();
let short = err.format_with_source_truncated(source, 60);
assert!(short.len() <= 60);
// Untrimmed output is the same as `format_with_source`:
let full = err.format_with_source(source);
let unbounded = err.format_with_source_truncated(source, full.len() + 100);
assert_eq!(unbounded, full);

pub fn format_with_source_radius_truncated( &self, source: &str, radius: usize, max_chars: usize, ) -> String

Format the error with multi-line radius context, capped at max_chars. Same truncation contract as Self::format_with_source_truncated.

§Examples
use noyalib::{from_str, Value};
let source = "a:\n  b:\n    c: [unclosed";
let err = from_str::<Value>(source).unwrap_err();
let s = err.format_with_source_radius_truncated(source, 1, 80);
assert!(s.len() <= 80);

pub fn into_shared(self) -> Arc<Error>

Convert the error into a shared Arc pointer. If the error is already Error::Shared, the inner Arc is reused without double-wrapping.

§Examples
let shared = noyalib::Error::EndOfStream.into_shared();
assert!(matches!(&*shared, noyalib::Error::EndOfStream));

pub fn is_shared(&self) -> bool

Check if the error is a shared error.

§Examples
use std::sync::Arc;
let e = noyalib::Error::Shared(Arc::new(noyalib::Error::EndOfStream));
assert!(e.is_shared());

pub fn as_inner(&self) -> Option<&Error>

Access the inner error if this is a shared error.

§Examples
use std::sync::Arc;
let e = noyalib::Error::Shared(Arc::new(noyalib::Error::EndOfStream));
assert!(e.as_inner().is_some());

pub fn parse_at(message: impl Into<String>, source: &str, index: usize) -> Error

Create a new parse error at the given index.

§Examples
let e = noyalib::Error::parse_at("bad", "a: x", 3);
assert!(matches!(e, noyalib::Error::ParseWithLocation { .. }));

pub fn deserialize_at( message: impl Into<String>, source: &str, index: usize, ) -> Error

Create a new deserialization error at the given index.

§Examples
let e = noyalib::Error::deserialize_at("bad", "a: x", 3);
assert!(matches!(e, noyalib::Error::DeserializeWithLocation { .. }));

pub fn from_shared(arc: Arc<Error>) -> Error

Create a new error from a shared error pointer.

§Examples
use std::sync::Arc;
let e = noyalib::Error::from_shared(Arc::new(noyalib::Error::EndOfStream));
assert!(e.is_shared());

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

Render the error in rustc-style with default options.

Equivalent to self.render_with_options(source, &RenderOptions::default()).

Issue #2 entry point — supersedes Self::format_with_source for new code; that method is preserved for backwards compatibility.

§Examples
use noyalib::{from_str, Value};
let source = "a:\n  b: 1\n   c: 2\n";  // misaligned indent
let err = from_str::<Value>(source).unwrap_err();
let rendered = err.render(source);
assert!(rendered.contains("error"));

pub fn render_with_options(&self, source: &str, opts: &RenderOptions) -> String

Render the error with caller-controlled options.

RenderOptions::crop_radius sets how many lines of context surround the offending line; RenderOptions::color enables terminal ANSI colour codes. The default (RenderOptions::default()) is crop_radius = 2, color = false.

§Examples
use noyalib::{from_str, RenderOptions, Value};
let source = "a: [unclosed";
let err = from_str::<Value>(source).unwrap_err();
let opts = RenderOptions { crop_radius: 1, color: false };
let rendered = err.render_with_options(source, &opts);
assert!(rendered.contains("error"));

Trait Implementations§

§

impl Debug for Error

§

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

Formats the value using the given formatter. Read more
§

impl Display for Error

§

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

Formats the value using the given formatter. Read more
§

impl Error for Error

Available on crate feature std only.
§

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
§

impl Error for Error

§

fn custom<T>(msg: T) -> Error
where T: Display,

Used when a Serialize implementation encounters any error while serializing a type. Read more
§

impl Error for Error

§

fn custom<T>(msg: T) -> Error
where T: Display,

Raised when there is general error when deserializing a type. Read more
§

fn missing_field(field: &'static str) -> Error

Raised when a Deserialize struct type expected to receive a required field with a particular name but that field was not present in the input.
§

fn unknown_field(field: &str, _expected: &'static [&'static str]) -> Error

Raised when a Deserialize struct type received a field with an unrecognized name.
Source§

fn invalid_type(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self

Raised when a Deserialize receives a type different from what it was expecting. Read more
Source§

fn invalid_value(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self

Raised when a Deserialize receives a value of the right type but that is wrong for some other reason. Read more
Source§

fn invalid_length(len: usize, exp: &dyn Expected) -> Self

Raised when deserializing a sequence or map and the input data contains too many or too few elements. Read more
Source§

fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self

Raised when a Deserialize enum type received a variant with an unrecognized name.
Source§

fn duplicate_field(field: &'static str) -> Self

Raised when a Deserialize struct type received more than one of the same field.
§

impl From<Error> for Error

Available on crate feature std only.
§

fn from(e: Error) -> Error

Converts to this type from the input type.
§

impl<'de> IntoDeserializer<'de, Error> for &'de Value

§

type Deserializer = &'de Value

The type of the deserializer being converted into.
§

fn into_deserializer( self, ) -> <&'de Value as IntoDeserializer<'de, Error>>::Deserializer

Convert this value into a deserializer.

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.