Skip to main content

agent_first_data/document/
error.rs

1//! Error types with context and helpful hints.
2
3use std::fmt;
4use std::io;
5
6pub type DocumentResult<T> = Result<T, DocumentError>;
7
8#[derive(Debug, Clone)]
9pub enum DocumentError {
10    EmptyPath,
11    EmptyValues,
12    UnknownSegment {
13        path: String,
14        segment: String,
15    },
16    /// A non-numeric segment addressed an array that nothing claims: no
17    /// [`KeyedList`](crate::document::KeyedList) registration covers it and its
18    /// format states no rule of its own.
19    ///
20    /// The message names the two ways out rather than the internal type that
21    /// happens to be missing — a caller can supply a rule or use an index, and
22    /// neither is discoverable from the name of a Rust struct.
23    UnregisteredArray {
24        path: String,
25    },
26    SlugNotFound {
27        prefix: String,
28        slug: String,
29    },
30    /// A non-numeric segment matched several elements of the array at `prefix`.
31    ///
32    /// Substring matching can produce this, as can an explicit keyed-list field
33    /// when an externally authored document contains duplicate identities.
34    /// Naming several things at once is not an address, and picking the first
35    /// would silently answer a different question than the one asked, so it is
36    /// refused with structural candidate indices.
37    ///
38    /// Candidate text is deliberately absent: an error must not become a route
39    /// for document content to bypass normal output redaction.
40    AmbiguousMatch {
41        prefix: String,
42        segment: String,
43        indices: Vec<usize>,
44    },
45    SlugAlreadyExists {
46        prefix: String,
47        slug: String,
48    },
49    NotTraversable {
50        path: String,
51        got: String,
52    },
53    /// An operation over a container's children — a `*` in a path pattern —
54    /// found `null` at `path`. Distinct from [`Self::NotContainer`] because a
55    /// `null` is commonly an unset collection, which a caller may well want to
56    /// read as empty, while a scalar there is a real shape mismatch.
57    NullContainer {
58        path: String,
59    },
60    /// An operation over a container's children found a scalar at `path`.
61    /// `got` is a [`Value::kind_name`](crate::document::Value::kind_name).
62    NotContainer {
63        path: String,
64        got: String,
65    },
66    TypeMismatch {
67        path: String,
68        expected: String,
69        got: String,
70        hint: Option<String>,
71    },
72    PathNotFound {
73        path: String,
74    },
75    IndexOutOfBounds {
76        path: String,
77        index: usize,
78        len: usize,
79    },
80    /// A parser rejected the source. `detail` is the parser's own text, which
81    /// quotes the offending line — see [`Self::redacted_message`].
82    ParseError {
83        format: String,
84        detail: String,
85    },
86    /// A dot-path is malformed: a bad escape, a trailing `\`, a bare `*`, an
87    /// index past the platform's range.
88    ///
89    /// Distinct from [`Self::ParseError`] because nothing here came from the
90    /// document — the caller's own address is what failed to parse, and
91    /// `detail` is afdata's own words about it. Sharing a code with a rejected
92    /// *file* sent readers to inspect the wrong thing.
93    PathSyntax {
94        detail: String,
95    },
96    /// afdata declines to read a source its parser would accept, because it
97    /// cannot answer honestly about it.
98    ///
99    /// `detail` is authored here and names the way out; it holds no document
100    /// text, so [`Self::redacted_message`] keeps it. Distinct from
101    /// [`Self::ParseError`] because the file is not malformed — reporting it as
102    /// a parse failure sends the reader hunting for a syntax error that is not
103    /// there.
104    SourceRefused {
105        format: String,
106        detail: String,
107    },
108    /// A caller argument contradicts itself or the document. `detail` is
109    /// afdata's own words about the argument, never document content.
110    InvalidArgument {
111        detail: String,
112    },
113    /// A staged edit rendered source this format's own parser rejects, caught
114    /// by the read-back in `save_atomic` before any bytes reached disk.
115    ///
116    /// `detail` is already redacted: it comes from
117    /// [`Self::redacted_message`] of the rejection, not from its `Display`.
118    WriteWouldCorrupt {
119        format: String,
120        detail: String,
121    },
122    /// No format could be inferred for `path`, so nothing was parsed at all.
123    ///
124    /// Distinct from [`Self::ParseError`] because it is about the file's name,
125    /// never its contents: it carries no document text, and dropping its detail
126    /// as a precaution would throw away the only actionable thing it says.
127    FormatUnknown {
128        path: String,
129    },
130    /// A create-only commit found an existing target. Kept separate from
131    /// [`Self::IoError`] so callers can safely implement idempotent create
132    /// workflows without parsing platform-specific I/O messages.
133    AlreadyExists {
134        path: String,
135    },
136    /// A capped read found more bytes than the caller allowed. Kept separate
137    /// from [`Self::IoError`] for the same reason as [`Self::AlreadyExists`]: a
138    /// caller enforcing a size budget has to tell "too big" from "missing" or
139    /// "unreadable", and should not have to match on a message to do it.
140    TooLarge {
141        path: String,
142        max_bytes: u64,
143    },
144    /// The source held zero bytes and its format has no empty document (an
145    /// empty JSON text is not JSON). `source` names where the bytes came from
146    /// (`stdin` or a path) so the reader looks at the producer, not at syntax.
147    EmptyInput {
148        source: String,
149    },
150    /// The file was installed, but its crash durability could not be confirmed.
151    CommitUncertain {
152        detail: String,
153    },
154    IoError {
155        detail: String,
156    },
157    UnsupportedOperation {
158        format: String,
159        operation: String,
160        detail: String,
161    },
162}
163
164impl fmt::Display for DocumentError {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        match self {
167            DocumentError::EmptyPath => {
168                write!(f, "empty path provided")
169            }
170            DocumentError::EmptyValues => {
171                write!(f, "at least one value required")
172            }
173            DocumentError::UnknownSegment { path, segment } => {
174                write!(f, "path `{path}` segment `{segment}` not found")
175            }
176            DocumentError::UnregisteredArray { path } => {
177                write!(
178                    f,
179                    "array at `{path}` has no rule for naming an element by its content; \
180                     address an element by index, or name the field that identifies one"
181                )
182            }
183            DocumentError::SlugNotFound { prefix, slug } => {
184                write!(f, "no element with slug `{slug}` found in `{prefix}`")
185            }
186            DocumentError::SlugAlreadyExists { prefix, slug } => {
187                write!(f, "slug `{slug}` already exists in `{prefix}`")
188            }
189            DocumentError::AmbiguousMatch {
190                prefix,
191                segment,
192                indices,
193            } => {
194                let candidates = indices
195                    .iter()
196                    .map(usize::to_string)
197                    .collect::<Vec<_>>()
198                    .join(", ");
199                write!(
200                    f,
201                    "segment `{}` matches {} elements of `{}` at indices {}",
202                    segment,
203                    indices.len(),
204                    prefix,
205                    candidates
206                )
207            }
208            // An empty prefix is the document itself: name it, and say what an empty
209            // document parses to, rather than print an empty pair of backticks.
210            DocumentError::NotTraversable { path, got } if path.is_empty() => {
211                if got == "null" {
212                    write!(
213                        f,
214                        "the document is empty (its root is null), cannot traverse into it"
215                    )
216                } else {
217                    write!(f, "the document root is {got}, cannot traverse into it")
218                }
219            }
220            DocumentError::NotTraversable { path, got } => {
221                write!(f, "path `{path}` is {got}, cannot traverse further")
222            }
223            DocumentError::NullContainer { path } if path.is_empty() => {
224                write!(
225                    f,
226                    "the document is empty (its root is null); there are no children"
227                )
228            }
229            DocumentError::NullContainer { path } => {
230                write!(f, "path `{path}` is null, so it has no children")
231            }
232            DocumentError::NotContainer { path, got } if path.is_empty() => {
233                write!(f, "the document root is {got}, which has no children")
234            }
235            DocumentError::NotContainer { path, got } => {
236                write!(f, "path `{path}` is {got}, which has no children")
237            }
238            DocumentError::TypeMismatch {
239                path,
240                expected,
241                got,
242                hint,
243            } => {
244                write!(f, "field `{path}` expects {expected}, got `{got}`")?;
245                if let Some(h) = hint {
246                    write!(f, "\n  hint: {h}")?;
247                }
248                Ok(())
249            }
250            DocumentError::PathNotFound { path } => {
251                write!(f, "path `{path}` not found in document")
252            }
253            DocumentError::IndexOutOfBounds { path, index, len } => {
254                write!(f, "index {index} out of bounds at `{path}` (len {len})")
255            }
256            DocumentError::ParseError { format, detail } => {
257                write!(f, "failed to parse {format}: {detail}")
258            }
259            DocumentError::PathSyntax { detail } => {
260                write!(f, "invalid path: {detail}")
261            }
262            DocumentError::SourceRefused { format, detail } => {
263                write!(f, "refusing to read this {format}: {detail}")
264            }
265            DocumentError::InvalidArgument { detail } => {
266                write!(f, "invalid argument: {detail}")
267            }
268            DocumentError::WriteWouldCorrupt { format, detail } => {
269                write!(
270                    f,
271                    "refusing to write: the edit produced {format} this parser rejects ({detail}); the file is unchanged"
272                )
273            }
274            DocumentError::FormatUnknown { path } => {
275                write!(
276                    f,
277                    "cannot detect the format of `{path}` from its extension; pass an explicit format"
278                )
279            }
280            DocumentError::AlreadyExists { path } => {
281                write!(f, "document target `{path}` already exists")
282            }
283            DocumentError::TooLarge { path, max_bytes } => {
284                write!(f, "`{path}` exceeds the {max_bytes}-byte read limit")
285            }
286            DocumentError::EmptyInput { source } => {
287                write!(
288                    f,
289                    "{source} is empty (zero bytes); there is no document to read"
290                )
291            }
292            DocumentError::IoError { detail } | DocumentError::CommitUncertain { detail } => {
293                write!(f, "io error: {detail}")
294            }
295            DocumentError::UnsupportedOperation {
296                format,
297                operation,
298                detail,
299            } => write!(f, "{format} does not support {operation}: {detail}"),
300        }
301    }
302}
303
304impl std::error::Error for DocumentError {}
305
306impl DocumentError {
307    /// Whether a complete new file may already have been installed.
308    pub const fn commit_uncertain(&self) -> bool {
309        matches!(self, Self::CommitUncertain { .. })
310    }
311
312    /// Stable, program-decidable error code for this failure category.
313    ///
314    /// Multiple variants share a code only when callers should handle them in
315    /// the same way. An ordinary missing path is `document_path_not_found`;
316    /// named array lookup distinguishes a missing slug from an ambiguous one.
317    #[must_use]
318    pub const fn code(&self) -> &'static str {
319        match self {
320            Self::ParseError { .. } => "document_parse_failed",
321            Self::PathSyntax { .. } => "document_invalid_path",
322            Self::SourceRefused { .. } => "document_source_refused",
323            Self::FormatUnknown { .. } => "document_format_unknown",
324            Self::AlreadyExists { .. } => "document_target_exists",
325            Self::TooLarge { .. } => "document_too_large",
326            Self::WriteWouldCorrupt { .. } => "document_write_would_corrupt",
327            Self::PathNotFound { .. }
328            | Self::UnknownSegment { .. }
329            | Self::IndexOutOfBounds { .. }
330            | Self::UnregisteredArray { .. } => "document_path_not_found",
331            Self::NotTraversable { .. } | Self::TypeMismatch { .. } => "document_type_mismatch",
332            Self::NullContainer { .. } => "document_null_value",
333            Self::NotContainer { .. } => "document_not_container",
334            Self::SlugNotFound { .. } => "document_slug_not_found",
335            Self::AmbiguousMatch { .. } => "document_ambiguous_match",
336            Self::SlugAlreadyExists { .. } => "document_slug_exists",
337            Self::EmptyInput { .. } => "document_empty",
338            Self::IoError { .. } | Self::CommitUncertain { .. } => "document_io_failed",
339            Self::UnsupportedOperation { .. } => "document_unsupported_operation",
340            Self::EmptyPath | Self::EmptyValues | Self::InvalidArgument { .. } => {
341                "document_invalid_argument"
342            }
343        }
344    }
345
346    /// Whether this error means "nothing is at that address": the family a
347    /// caller with a fallback for an absent value is entitled to swallow.
348    ///
349    /// A structural miss (no such key, an index past the end, an array nothing
350    /// names elements of) and a named miss (no element matched) qualify, and so
351    /// does a path that runs *through* a scalar ([`Self::NotTraversable`]):
352    /// nothing is at `b.version` when `b` is a string either.
353    /// [`Self::AmbiguousMatch`] deliberately does not — several elements
354    /// answered, so there is something there, just not one thing — and neither
355    /// does a [`Self::TypeMismatch`], which is a real fault.
356    #[must_use]
357    pub fn is_address_miss(&self) -> bool {
358        matches!(
359            self,
360            Self::PathNotFound { .. }
361                | Self::UnknownSegment { .. }
362                | Self::IndexOutOfBounds { .. }
363                | Self::UnregisteredArray { .. }
364                | Self::SlugNotFound { .. }
365                | Self::NotTraversable { .. }
366        )
367    }
368
369    /// Best-effort, content-free source location for a parse failure.
370    ///
371    /// Returns e.g. `"line 5 column 12"` (or `"line 5"`) for a
372    /// [`DocumentError::ParseError`], and `None` for every other variant or
373    /// when the underlying parser reported no position. The returned string is
374    /// derived from the parser's position only and never contains document
375    /// content, so it is safe to surface even when the parsed file may hold
376    /// secrets.
377    #[must_use]
378    pub fn location(&self) -> Option<String> {
379        let Self::ParseError { detail, .. } = self else {
380            return None;
381        };
382        // A parser diagnostic opens with its own position and echoes the
383        // offending source on the lines below it:
384        //
385        //     TOML parse error at line 2, column 5
386        //       |
387        //     2 | note = "see at line 999 for details" bad
388        //
389        // So the position is on the first line and document content never is.
390        // Searching the whole detail — from either end — can read the echo:
391        // from the end it finds `at line 999`, which is the file's own text.
392        let head = detail.split('\n').next().unwrap_or(detail);
393        let rest = match head.split_once(" at line ") {
394            Some((_, rest)) => rest,
395            None => head.strip_prefix("line ")?,
396        };
397        let line = leading_ascii_digits(rest)?;
398        let column = rest
399            .split_once("column ")
400            .and_then(|(_, tail)| leading_ascii_digits(tail));
401        Some(match column {
402            Some(column) => format!("line {line} column {column}"),
403            None => format!("line {line}"),
404        })
405    }
406
407    /// A display message with any potentially content-bearing detail removed —
408    /// safe to surface when the document may hold secrets.
409    ///
410    /// Two variants can quote material that originates in the document and are
411    /// rewritten here:
412    ///
413    /// - [`DocumentError::ParseError`] renders as `failed to parse {format}`
414    ///   (with the [`location`](Self::location) appended when known), dropping
415    ///   the parser detail, which echoes a snippet of the source.
416    ///
417    /// [`DocumentError::PathSyntax`], [`DocumentError::SourceRefused`] and
418    /// [`DocumentError::InvalidArgument`] keep their detail in full. It is the
419    /// reason they exist as separate variants: their text is written here, about
420    /// the caller's address, argument, or file *encoding* — never lifted from
421    /// document content — and it is the only part that says what to do next.
422    /// Dropping it as a precaution against a leak that cannot happen turned an
423    /// actionable refusal into `failed to parse Markdown`.
424    /// - [`DocumentError::TypeMismatch`] drops `got` and `hint`. When built by
425    ///   [`Self::from_serde`] those carry serde's rendering of the offending
426    ///   value, which is document content.
427    ///
428    /// Every other variant renders the same as its [`std::fmt::Display`], carrying only
429    /// structural context: paths, requested slugs, indices, and type or format
430    /// names. In particular, [`Self::AmbiguousMatch`] carries candidate indices
431    /// rather than matched field values.
432    /// [`DocumentError::NotTraversable`] belongs to that group because `got` is
433    /// a [`Value::kind_name`](crate::document::Value::kind_name), not a value.
434    #[must_use]
435    pub fn redacted_message(&self) -> String {
436        match self {
437            // afdata's own sentence about a binary property list read as the
438            // wrong format: it names the flag and quotes nothing from the file.
439            #[cfg(feature = "plist")]
440            Self::ParseError { detail, .. }
441                if detail == crate::document::format::plist::WRONG_FORMAT_DETAIL
442                    || detail == crate::document::format::plist::WRONG_FORMAT_XML_DETAIL =>
443            {
444                self.to_string()
445            }
446            Self::ParseError { format, .. } => match self.location() {
447                Some(location) => format!("failed to parse {format} at {location}"),
448                None => format!("failed to parse {format}"),
449            },
450            Self::TypeMismatch { path, expected, .. } => {
451                if expected.is_empty() {
452                    format!("field `{path}` has the wrong type")
453                } else {
454                    format!("field `{path}` expects {expected}")
455                }
456            }
457            other => other.to_string(),
458        }
459    }
460
461    /// Wrap a serde deserialization failure as a `TypeMismatch` so callers that
462    /// do a read-modify-write cycle (set_path → serde round-trip) surface a
463    /// consistent error style rather than a raw serde message.
464    pub fn from_serde(path: impl Into<String>, err: impl std::fmt::Display) -> Self {
465        let msg = err.to_string();
466        // serde messages look like "invalid type: string \"x\", expected u16 at …"
467        // Strip the trailing " at line N column M" to keep the hint concise.
468        let hint = msg
469            .split(" at line ")
470            .next()
471            .unwrap_or(&msg)
472            .trim()
473            .to_string();
474        DocumentError::TypeMismatch {
475            path: path.into(),
476            expected: String::new(),
477            got: hint,
478            hint: None,
479        }
480    }
481}
482
483impl From<io::Error> for DocumentError {
484    fn from(err: io::Error) -> Self {
485        DocumentError::IoError {
486            detail: err.to_string(),
487        }
488    }
489}
490
491fn leading_ascii_digits(text: &str) -> Option<&str> {
492    let end = text.bytes().take_while(u8::is_ascii_digit).count();
493    (end > 0).then_some(&text[..end])
494}
495
496#[cfg(test)]
497mod tests {
498    use super::DocumentError;
499
500    #[test]
501    fn document_error_codes_are_stable() {
502        let cases = [
503            (DocumentError::EmptyPath, "document_invalid_argument"),
504            (DocumentError::EmptyValues, "document_invalid_argument"),
505            (
506                DocumentError::UnknownSegment {
507                    path: "root.key".to_string(),
508                    segment: "key".to_string(),
509                },
510                "document_path_not_found",
511            ),
512            (
513                DocumentError::UnregisteredArray {
514                    path: "items".to_string(),
515                },
516                "document_path_not_found",
517            ),
518            (
519                DocumentError::SlugNotFound {
520                    prefix: "items".to_string(),
521                    slug: "missing".to_string(),
522                },
523                "document_slug_not_found",
524            ),
525            (
526                DocumentError::SlugAlreadyExists {
527                    prefix: "items".to_string(),
528                    slug: "existing".to_string(),
529                },
530                "document_slug_exists",
531            ),
532            (
533                DocumentError::AmbiguousMatch {
534                    prefix: "items".to_string(),
535                    segment: "look".to_string(),
536                    indices: vec![0, 2],
537                },
538                "document_ambiguous_match",
539            ),
540            (
541                DocumentError::NotTraversable {
542                    path: "root".to_string(),
543                    got: "string".to_string(),
544                },
545                "document_type_mismatch",
546            ),
547            (
548                DocumentError::TypeMismatch {
549                    path: "root.key".to_string(),
550                    expected: "integer".to_string(),
551                    got: "string".to_string(),
552                    hint: None,
553                },
554                "document_type_mismatch",
555            ),
556            (
557                DocumentError::PathNotFound {
558                    path: "root.key".to_string(),
559                },
560                "document_path_not_found",
561            ),
562            (
563                DocumentError::EmptyInput {
564                    source: "stdin".to_string(),
565                },
566                "document_empty",
567            ),
568            (
569                DocumentError::IndexOutOfBounds {
570                    path: "items".to_string(),
571                    index: 2,
572                    len: 1,
573                },
574                "document_path_not_found",
575            ),
576            (
577                DocumentError::ParseError {
578                    format: "JSON".to_string(),
579                    detail: "invalid input".to_string(),
580                },
581                "document_parse_failed",
582            ),
583            (
584                DocumentError::IoError {
585                    detail: "unreadable".to_string(),
586                },
587                "document_io_failed",
588            ),
589            (
590                DocumentError::AlreadyExists {
591                    path: "config.toml".to_string(),
592                },
593                "document_target_exists",
594            ),
595            (
596                DocumentError::TooLarge {
597                    path: "config.toml".to_string(),
598                    max_bytes: 1024,
599                },
600                "document_too_large",
601            ),
602            (
603                DocumentError::UnsupportedOperation {
604                    format: "INI".to_string(),
605                    operation: "set".to_string(),
606                    detail: "unsupported".to_string(),
607                },
608                "document_unsupported_operation",
609            ),
610        ];
611
612        for (error, expected) in cases {
613            assert_eq!(error.code(), expected);
614        }
615    }
616
617    #[test]
618    fn location_extracts_position_without_content() {
619        // The real layout a parser produces: its own position first, then the
620        // offending source echoed below. The echo here carries `at line 999`
621        // out of the document, and a search from the end reads exactly that —
622        // reporting a wrong line and leaking a document-derived number through
623        // `redacted_message`, which promises never to surface file content.
624        let err = DocumentError::ParseError {
625            format: "TOML".to_string(),
626            detail: "TOML parse error at line 5, column 12\n  |\n\
627                     5 | note = \"see at line 999 for TOPSECRET\" bad\n  |     ^"
628                .to_string(),
629        };
630        assert_eq!(err.location().as_deref(), Some("line 5 column 12"));
631        assert!(!err.redacted_message().contains("999"));
632        assert!(!err.redacted_message().contains("TOPSECRET"));
633
634        let no_column = DocumentError::ParseError {
635            format: "JSON".to_string(),
636            detail: "boom at line 3".to_string(),
637        };
638        assert_eq!(no_column.location().as_deref(), Some("line 3"));
639
640        // No position, and non-parse variants, carry no location.
641        assert!(
642            DocumentError::ParseError {
643                format: "INI".to_string(),
644                detail: "sensitive value".to_string(),
645            }
646            .location()
647            .is_none()
648        );
649        assert!(
650            DocumentError::PathNotFound {
651                path: "a.b".to_string(),
652            }
653            .location()
654            .is_none()
655        );
656    }
657
658    #[test]
659    fn redacted_message_drops_parser_detail() {
660        let err = DocumentError::ParseError {
661            format: "YAML".to_string(),
662            detail: "unexpected TOPSECRET at line 5 column 12".to_string(),
663        };
664        let redacted = err.redacted_message();
665        assert_eq!(redacted, "failed to parse YAML at line 5 column 12");
666        assert!(!redacted.contains("TOPSECRET"));
667
668        // Structural variants pass through unchanged.
669        let path_err = DocumentError::PathNotFound {
670            path: "database.url".to_string(),
671        };
672        assert_eq!(path_err.redacted_message(), path_err.to_string());
673    }
674
675    #[test]
676    fn redacted_message_drops_the_offending_value() {
677        // `from_serde` keeps serde's rendering, which quotes the value that
678        // failed the type check — document content, and a secret as often as not.
679        let err = DocumentError::from_serde(
680            "credentials.token",
681            "invalid type: string \"sk-live-TOPSECRET\", expected u16",
682        );
683        assert!(err.to_string().contains("sk-live-TOPSECRET"));
684        let redacted = err.redacted_message();
685        assert!(!redacted.contains("sk-live-TOPSECRET"), "{redacted}");
686        assert!(redacted.contains("credentials.token"), "{redacted}");
687    }
688
689    #[test]
690    fn ambiguous_match_reports_indices_without_document_content() {
691        let err = DocumentError::AmbiguousMatch {
692            prefix: "h1.0.h2".to_string(),
693            segment: "look".to_string(),
694            indices: vec![0, 2],
695        };
696        assert_eq!(
697            err.redacted_message(),
698            "segment `look` matches 2 elements of `h1.0.h2` at indices 0, 2"
699        );
700        assert!(!err.redacted_message().contains("Quick look"));
701    }
702
703    #[test]
704    fn not_traversable_names_the_type_not_the_value() {
705        // This one is safe by construction rather than by redaction: `got` is a
706        // kind name, so even `Display` cannot echo the leaf.
707        let err = DocumentError::NotTraversable {
708            path: "token_secret.inner".to_string(),
709            got: crate::document::Value::String("sk-live-TOPSECRET".to_string())
710                .kind_name()
711                .to_string(),
712        };
713        assert_eq!(
714            err.to_string(),
715            "path `token_secret.inner` is string, cannot traverse further"
716        );
717        assert_eq!(err.redacted_message(), err.to_string());
718    }
719
720    #[test]
721    fn not_traversable_at_the_root_names_the_document() {
722        let empty = DocumentError::NotTraversable {
723            path: String::new(),
724            got: "null".to_string(),
725        };
726        assert_eq!(
727            empty.to_string(),
728            "the document is empty (its root is null), cannot traverse into it"
729        );
730        let scalar = DocumentError::NotTraversable {
731            path: String::new(),
732            got: "string".to_string(),
733        };
734        assert_eq!(
735            scalar.to_string(),
736            "the document root is string, cannot traverse into it"
737        );
738    }
739}