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