Skip to main content

i18n_next/
error.rs

1//! The crate's error (DESIGN 4.5): hand-written `Display` and `Error`, no `thiserror` (2.3).
2
3use std::fmt;
4
5/// What went wrong while building the catalog or switching it.
6///
7/// A broken or non-object locale file is an error with its path. The JS loader logs it and
8/// skips the file; Rust refuses to start with half a catalog instead.
9#[derive(Debug)]
10#[non_exhaustive]
11pub enum Error {
12    /// A file or directory could not be read.
13    Io {
14        /// The path as given (a `dir` entry is joined to its directory).
15        path: String,
16        /// What the OS said.
17        source: std::io::Error,
18    },
19    /// A locale file, `messages` text or `i18n.json` is not valid JSON.
20    Json {
21        /// The file path, or `messages:<locale>/<page>` for text passed in code.
22        path: String,
23        /// Byte offset of the problem (a BOM counts).
24        offset: usize,
25        /// What is wrong there.
26        kind: &'static str,
27    },
28    /// Valid JSON, but not an object (an array, `null`, a string…).
29    NotObject {
30        /// The file path, or `messages:<locale>/<page>`.
31        path: String,
32    },
33    /// A locale that no file, `i18n.json` entry or builder call names.
34    UnknownLocale(String),
35    /// A locale `i18n.json` marks `"disabled": true`.
36    DisabledLocale(String),
37    /// A page name that is not allowed or not known (`__proto__`, an alias to nothing).
38    UnknownPage(String),
39    /// `i18n.json` has the wrong shape.
40    Config {
41        /// The config path, or `i18n.json` for `config_json`.
42        path: String,
43        /// Which field is wrong.
44        reason: &'static str,
45    },
46    /// A path `add_file` was given that the `remote` manifest does not list (8b.2: names
47    /// only from the catalog).
48    UnknownFile(String),
49    /// `install` was called while an instance is installed already.
50    AlreadyInstalled,
51    /// A free function (`set_locale`) needs an instance: none is installed, no scope sets one.
52    NotInstalled,
53    /// A named format (`numberFormats` / `datetimeFormats` of `i18n.json`,
54    /// `Builder::formats` / `Builder::datetime_formats`) uses an `Intl` option outside the
55    /// supported subset (`signDisplay: "always"`, `style: "unit"`, `timeStyle: "full"`,
56    /// `timeZoneName`…) or a value `Intl` throws on (`currency: "usdx"`,
57    /// `minimumFractionDigits` over `maximumFractionDigits`, `month: "numerical"`, a time
58    /// zone the platform does not know): refused at `build` rather than formatted
59    /// differently from the front end.
60    UnsupportedFormat {
61        /// The locale code the format is listed under.
62        locale: String,
63        /// The format's name.
64        name: String,
65        /// The option (`signDisplay`, `notation`, `maximumFractionDigits`…).
66        option: String,
67    },
68    /// `Builder::time_zone` names a zone the platform does not know (JS `RangeError`); without
69    /// the `tz` feature only UTC is known.
70    UnknownTimeZone(String),
71    /// The fetch closure of `ensure_async` failed for one file; the catalog is unchanged.
72    Fetch {
73        /// The manifest path that was being fetched.
74        path: String,
75        /// What the closure's error said (its `Display`).
76        message: String,
77    },
78}
79
80impl fmt::Display for Error {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        match self {
83            Error::Io { path, source } => write!(f, "cannot read {path}: {source}"),
84            Error::Json { path, offset, kind } => {
85                write!(f, "{path}: invalid JSON at byte {offset}: {kind}")
86            }
87            Error::NotObject { path } => write!(f, "{path}: expected a JSON object"),
88            Error::UnknownLocale(code) => write!(f, "unknown locale \"{code}\""),
89            Error::DisabledLocale(code) => write!(f, "locale \"{code}\" is disabled"),
90            Error::UnknownPage(name) => write!(f, "unknown page \"{name}\""),
91            Error::Config { path, reason } => write!(f, "{path}: {reason}"),
92            Error::UnknownFile(path) => write!(f, "unknown file \"{path}\""),
93            Error::Fetch { path, message } => write!(f, "cannot fetch {path}: {message}"),
94            Error::UnsupportedFormat {
95                locale,
96                name,
97                option,
98            } => write!(
99                f,
100                "format \"{name}\" of \"{locale}\": option \"{option}\" is not supported"
101            ),
102            Error::UnknownTimeZone(name) => write!(f, "unknown time zone \"{name}\""),
103            Error::AlreadyInstalled => f.write_str("an i18n instance is installed already"),
104            Error::NotInstalled => {
105                f.write_str("no i18n instance: install() one or set it in a scope")
106            }
107        }
108    }
109}
110
111impl Error {
112    /// A copy for every waiter of one shared fetch (`Error` is not `Clone`: `Io` holds an
113    /// `io::Error`, which `add_file` never returns; anything else becomes `Fetch` with its
114    /// text).
115    pub(crate) fn duplicate(&self, file: &str) -> Error {
116        match self {
117            Error::Json { path, offset, kind } => Error::Json {
118                path: path.clone(),
119                offset: *offset,
120                kind,
121            },
122            Error::NotObject { path } => Error::NotObject { path: path.clone() },
123            Error::Fetch { path, message } => Error::Fetch {
124                path: path.clone(),
125                message: message.clone(),
126            },
127            other => Error::Fetch {
128                path: file.to_owned(),
129                message: other.to_string(),
130            },
131        }
132    }
133}
134
135impl std::error::Error for Error {
136    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
137        match self {
138            Error::Io { source, .. } => Some(source),
139            _ => None,
140        }
141    }
142}