Skip to main content

DecodeError

Struct DecodeError 

Source
pub struct DecodeError(/* private fields */);
Expand description

Why a typed value could not be read: what went wrong, at which byte, and where in the document.

The path is built as the error travels out through the containers it was found in, so it costs nothing until something fails. pointer gives it as an RFC 6901 JSON Pointer, which is what Display shows after the offset: expected u32, found string at byte 31 (at /position/line). That is a ready-made message for a JSON-RPC -32602 Invalid params reply.

The keys in the path come from the input, so the message shows them made safe to log: a control character, a line or paragraph separator, or a bidirectional formatting character is written as its Rust escape (\u{a} for a newline), a backslash as \\, and a key longer than 64 characters is cut there and ends in .... The message is therefore always one line, and its length is bounded by the depth of the path. path and pointer keep every key exact.

The error is one pointer wide, so Result<T, DecodeError> stays small.

§Examples

use jsonx_lib::{DecodeErrorKind, Kind, PathSegment};

let err = jsonx_lib::from_str::<Vec<Vec<u8>>>("[[1], [2, true]]").unwrap_err();
assert_eq!(err.kind(), &DecodeErrorKind::WrongType { expected: "u8", found: Kind::Bool });
assert_eq!(err.offset(), 10);
assert_eq!(err.path(), [PathSegment::Index(1), PathSegment::Index(1)]);
assert_eq!(err.pointer(), "/1/1");
assert_eq!(err.to_string(), "expected u8, found boolean at byte 10 (at /1/1)");

Implementations§

Source§

impl DecodeError

Source

pub fn new(kind: DecodeErrorKind, offset: usize) -> Self

An error of kind at byte offset, with an empty path.

§Examples
use jsonx_lib::{DecodeError, DecodeErrorKind};

let err = DecodeError::new(DecodeErrorKind::InvalidValue("a port"), 12);
assert_eq!(err.to_string(), "invalid value: expected a port at byte 12");
Source

pub fn wrong_type(expected: &'static str, found: Kind, offset: usize) -> Self

A DecodeErrorKind::WrongType error.

§Examples
use jsonx_lib::{DecodeError, Kind};

let err = DecodeError::wrong_type("a position", Kind::Array, 4);
assert_eq!(err.to_string(), "expected a position, found array at byte 4");
Source

pub fn invalid_value(expected: &'static str, offset: usize) -> Self

A DecodeErrorKind::InvalidValue error.

§Examples
let err = jsonx_lib::DecodeError::invalid_value("a URI", 0);
assert_eq!(err.to_string(), "invalid value: expected a URI at byte 0");
Source

pub fn custom(message: impl Into<Cow<'static, str>>, offset: usize) -> Self

A DecodeErrorKind::Custom error with message.

§Examples
let err = jsonx_lib::DecodeError::custom("end before start", 9);
assert_eq!(err.to_string(), "end before start at byte 9");
Source

pub fn missing_field(name: &'static str, offset: usize) -> Self

A DecodeErrorKind::MissingField error.

§Examples
let err = jsonx_lib::DecodeError::missing_field("uri", 0);
assert_eq!(err.to_string(), "missing field `uri` at byte 0");
Source

pub fn at_key(self, key: impl Into<String>) -> Self

The error as seen from the object that holds it under key: the key goes in front of the path. The object readers do this for you.

§Examples
let err = jsonx_lib::DecodeError::invalid_value("a URI", 7).at_key("uri").at_key("textDocument");
assert_eq!(err.pointer(), "/textDocument/uri");
Source

pub fn at_index(self, index: usize) -> Self

The error as seen from the array that holds it at index.

§Examples
let err = jsonx_lib::DecodeError::invalid_value("a URI", 7).at_index(2);
assert_eq!(err.pointer(), "/2");
Source

pub fn kind(&self) -> &DecodeErrorKind

What went wrong.

Source

pub fn offset(&self) -> usize

The byte offset in the input where it went wrong: the value that did not fit, or for a syntax error the byte a parse reports.

Source

pub fn path(&self) -> &[PathSegment]

Where in the document, outermost first; empty for the top-level value.

Source

pub fn pointer(&self) -> String

The path as an RFC 6901 JSON Pointer (/params/items/3, "" for the top level), usable with Value::pointer.

§Examples
let err = jsonx_lib::DecodeError::invalid_value("x", 0).at_key("a/b").at_key("~");
assert_eq!(err.pointer(), "/~0/a~1b");
Source

pub fn line_col(&self, input: impl AsRef<[u8]>) -> (usize, usize)

The error’s line and column in input, from 1, the column in characters; see Error::line_col.

§Examples
let text = "{\n  \"n\": \"seven\"\n}";
let err = jsonx_lib::from_str::<std::collections::BTreeMap<String, u8>>(text).unwrap_err();
assert_eq!(err.line_col(text), (2, 8));
Source

pub fn utf16_position(&self, input: impl AsRef<[u8]>) -> (usize, usize)

The error’s position in input as LSP counts it (from 0, the character in UTF-16 units); see Error::utf16_position.

§Examples
let text = "[1,\n \"x\"]";
let err = jsonx_lib::from_str::<Vec<u8>>(text).unwrap_err();
assert_eq!(err.utf16_position(text), (1, 1));
Source

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

The parse error, for a DecodeErrorKind::Syntax error.

§Examples
use jsonx_lib::ErrorKind;

let err = jsonx_lib::from_str::<Vec<u8>>("[1,]").unwrap_err();
assert_eq!(err.syntax_error().map(|e| e.kind()), Some(ErrorKind::TrailingComma));

Trait Implementations§

Source§

impl Clone for DecodeError

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DecodeError

Source§

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

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

impl Display for DecodeError

Source§

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

The message, with the path’s keys made safe to log (see DecodeError).

Source§

impl Eq for DecodeError

Source§

impl Error for DecodeError

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<Error> for DecodeError

Source§

fn from(e: Error) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for DecodeError

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for DecodeError

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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 = !

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

fn try_from(value: U) -> Result<T, !>

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.