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.8")]
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 /// Element path at which this deserialization error occurred.
88 pub fn path(&self) -> &Path {
89 &self.path
90 }
91
92 /// The Deserializer's underlying error that occurred.
93 pub fn into_inner(self) -> E {
94 self.original
95 }
96
97 /// Reference to the Deserializer's underlying error that occurred.
98 pub fn inner(&self) -> &E {
99 &self.original
100 }
101}
102
103impl<E: Display> Display for Error<E> {
104 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
105 write!(f, "{}: {}", self.path(), self.inner())
106 }
107}
108
109impl<E: StdError + 'static> StdError for Error<E> {
110 fn source(&self) -> Option<&(dyn StdError + 'static)> {
111 Some(self.inner())
112 }
113}
114
115/// State for bookkeeping across nested deserializer calls.
116///
117/// You don't need this if you are using `serde_path_to_error::deserializer`. If
118/// you are managing your own `Deserializer`, see the usage example on
119/// [`Deserializer`].
120pub struct Track {
121 path: Cell<Option<Path>>,
122}
123
124impl Track {
125 /// Empty state with no error having happened yet.
126 pub fn new() -> Self {
127 Track {
128 path: Cell::new(None),
129 }
130 }
131
132 /// Gets path at which the error occurred. Only meaningful after we know
133 /// that an error has occurred. Returns an empty path otherwise.
134 pub fn path(self) -> Path {
135 self.path.into_inner().unwrap_or_else(Path::empty)
136 }
137
138 #[inline]
139 fn trigger<E>(&self, chain: &Chain, err: E) -> E {
140 self.trigger_impl(chain);
141 err
142 }
143
144 fn trigger_impl(&self, chain: &Chain) {
145 self.path.set(Some(match self.path.take() {
146 Some(already_set) => already_set,
147 None => Path::from_chain(chain),
148 }));
149 }
150}
151
152#[derive(Clone)]
153enum Chain<'a> {
154 Root,
155 Seq {
156 parent: &'a Chain<'a>,
157 index: usize,
158 },
159 Map {
160 parent: &'a Chain<'a>,
161 key: String,
162 },
163 Struct {
164 parent: &'a Chain<'a>,
165 key: &'static str,
166 },
167 Enum {
168 parent: &'a Chain<'a>,
169 variant: String,
170 },
171 Some {
172 parent: &'a Chain<'a>,
173 },
174 NewtypeStruct {
175 parent: &'a Chain<'a>,
176 },
177 NewtypeVariant {
178 parent: &'a Chain<'a>,
179 },
180 NonStringKey {
181 parent: &'a Chain<'a>,
182 },
183}