serde_path_to_error/
lib.rs

1//! [![github]](https://github.com/dtolnay/path-to-error) [![crates-io]](https://crates.io/crates/serde_path_to_error) [![docs-rs]](https://docs.rs/serde_path_to_error)
2//!
3//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
4//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
6//!
7//! <br>
8//!
9//! Find out the path at which a deserialization error occurred. This crate
10//! provides a wrapper that works with any existing Serde `Deserializer` and
11//! exposes the chain of field names leading to the error.
12//!
13//! # Example
14//!
15//! ```
16//! # use serde_derive::Deserialize;
17//! #
18//! use serde::Deserialize;
19//! use std::collections::BTreeMap as Map;
20//!
21//! #[derive(Deserialize)]
22//! struct Package {
23//!     name: String,
24//!     dependencies: Map<String, Dependency>,
25//! }
26//!
27//! #[derive(Deserialize)]
28//! struct Dependency {
29//!     version: String,
30//! }
31//!
32//! fn main() {
33//!     let j = r#"{
34//!         "name": "demo",
35//!         "dependencies": {
36//!             "serde": {
37//!                 "version": 1
38//!             }
39//!         }
40//!     }"#;
41//!
42//!     // Some Deserializer.
43//!     let jd = &mut serde_json::Deserializer::from_str(j);
44//!
45//!     let result: Result<Package, _> = serde_path_to_error::deserialize(jd);
46//!     match result {
47//!         Ok(_) => panic!("expected a type error"),
48//!         Err(err) => {
49//!             let path = err.path().to_string();
50//!             assert_eq!(path, "dependencies.serde.version");
51//!         }
52//!     }
53//! }
54//! ```
55
56#![doc(html_root_url = "https://docs.rs/serde_path_to_error/0.1.16")]
57#![allow(
58    clippy::doc_link_with_quotes, // https://github.com/rust-lang/rust-clippy/issues/8961
59    clippy::iter_not_returning_iterator, // https://github.com/rust-lang/rust-clippy/issues/8285
60    clippy::missing_errors_doc,
61    clippy::module_name_repetitions,
62    clippy::must_use_candidate,
63    clippy::new_without_default
64)]
65
66mod de;
67mod path;
68mod ser;
69mod wrap;
70
71use std::cell::Cell;
72use std::error::Error as StdError;
73use std::fmt::{self, Display};
74
75pub use crate::de::{deserialize, Deserializer};
76pub use crate::path::{Path, Segment, Segments};
77pub use crate::ser::{serialize, Serializer};
78
79/// Original deserializer error together with the path at which it occurred.
80#[derive(Clone, Debug)]
81pub struct Error<E> {
82    path: Path,
83    original: E,
84}
85
86impl<E> Error<E> {
87    pub fn new(path: Path, inner: E) -> Self {
88        Error {
89            path,
90            original: inner,
91        }
92    }
93
94    /// Element path at which this deserialization error occurred.
95    pub fn path(&self) -> &Path {
96        &self.path
97    }
98
99    /// The Deserializer's underlying error that occurred.
100    pub fn into_inner(self) -> E {
101        self.original
102    }
103
104    /// Reference to the Deserializer's underlying error that occurred.
105    pub fn inner(&self) -> &E {
106        &self.original
107    }
108}
109
110impl<E: Display> Display for Error<E> {
111    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
112        if !self.path.is_only_unknown() {
113            write!(f, "{}: ", self.path)?;
114        }
115        write!(f, "{}", self.original)
116    }
117}
118
119impl<E: StdError> StdError for Error<E> {
120    fn source(&self) -> Option<&(dyn StdError + 'static)> {
121        self.original.source()
122    }
123}
124
125/// State for bookkeeping across nested deserializer calls.
126///
127/// You don't need this if you are using `serde_path_to_error::deserializer`. If
128/// you are managing your own `Deserializer`, see the usage example on
129/// [`Deserializer`].
130pub struct Track {
131    path: Cell<Option<Path>>,
132}
133
134impl Track {
135    /// Empty state with no error having happened yet.
136    pub const fn new() -> Self {
137        Track {
138            path: Cell::new(None),
139        }
140    }
141
142    /// Gets path at which the error occurred. Only meaningful after we know
143    /// that an error has occurred. Returns an empty path otherwise.
144    pub fn path(self) -> Path {
145        self.path.into_inner().unwrap_or_else(Path::empty)
146    }
147
148    #[inline]
149    fn trigger<E>(&self, chain: &Chain, err: E) -> E {
150        self.trigger_impl(chain);
151        err
152    }
153
154    fn trigger_impl(&self, chain: &Chain) {
155        self.path.set(Some(match self.path.take() {
156            Some(already_set) => already_set,
157            None => Path::from_chain(chain),
158        }));
159    }
160}
161
162#[derive(Clone)]
163enum Chain<'a> {
164    Root,
165    Seq {
166        parent: &'a Chain<'a>,
167        index: usize,
168    },
169    Map {
170        parent: &'a Chain<'a>,
171        key: String,
172    },
173    Struct {
174        parent: &'a Chain<'a>,
175        key: &'static str,
176    },
177    Enum {
178        parent: &'a Chain<'a>,
179        variant: String,
180    },
181    Some {
182        parent: &'a Chain<'a>,
183    },
184    NewtypeStruct {
185        parent: &'a Chain<'a>,
186    },
187    NewtypeVariant {
188        parent: &'a Chain<'a>,
189    },
190    NonStringKey {
191        parent: &'a Chain<'a>,
192    },
193}