star_toml/error.rs
1//! Error types for `star_toml`.
2
3use crate::validation::ValidationErrors;
4use std::path::PathBuf;
5
6/// Alias so callers can write `star_toml::Result<T>`.
7pub type Result<T> = std::result::Result<T, Error>;
8
9/// Everything that can go wrong while loading, merging, or validating a TOML config.
10#[derive(Debug, thiserror::Error)]
11pub enum Error {
12 /// No file matching the requested name was found by walking parent directories.
13 #[error("config file not found: {0}")]
14 FileNotFound(PathBuf),
15
16 /// OS-level I/O error (permissions, missing dir, etc.).
17 #[error("I/O error reading {path}: {source}")]
18 Io {
19 path: PathBuf,
20 #[source]
21 source: std::io::Error,
22 },
23
24 /// The TOML text could not be parsed.
25 #[error("TOML parse error in {path}: {source}")]
26 Parse {
27 /// The file or description ("inline string") where the error occurred.
28 path: String,
29 #[source]
30 source: toml::de::Error,
31 },
32
33 /// A config value could not be serialized back to TOML.
34 #[error("TOML serialize error: {0}")]
35 Serialize(#[from] toml::ser::Error),
36
37 /// A loaded config failed its own invariant checks (see [`crate::Validate`]).
38 ///
39 /// Used for ad-hoc, single-message validation. For structured, path-precise,
40 /// multi-error reports, see [`Error::Invalid`].
41 #[error("validation failed for {context}: {reason}")]
42 Validation {
43 /// Which file or config type was being validated.
44 context: String,
45 /// Human-readable description of the violation.
46 reason: String,
47 },
48
49 /// A loaded config failed structured validation — carries the full
50 /// path-precise report of every failure (see [`crate::ValidationErrors`]).
51 #[error("{0}")]
52 Invalid(#[from] ValidationErrors),
53}
54
55impl Error {
56 /// Construct a validation error.
57 pub fn validation(context: impl Into<String>, reason: impl Into<String>) -> Self {
58 Self::Validation {
59 context: context.into(),
60 reason: reason.into(),
61 }
62 }
63
64 /// Construct an I/O error with source path context.
65 pub fn io(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
66 Self::Io {
67 path: path.into(),
68 source,
69 }
70 }
71
72 /// Construct a parse error with file/location context.
73 pub fn parse(path: impl Into<String>, source: toml::de::Error) -> Self {
74 Self::Parse {
75 path: path.into(),
76 source,
77 }
78 }
79}