Skip to content

Commit b690542

Browse files
committed
Better error message when a translation file fails to load
1 parent c6e85ed commit b690542

File tree

1 file changed

+54
-11
lines changed

1 file changed

+54
-11
lines changed

crates/i18n/src/translator.rs

Lines changed: 54 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,37 @@ const FALLBACKER: LocaleFallbackerWithConfig<'static> = LocaleFallbacker::new().
3636

3737
/// Error type for loading translations
3838
#[derive(Debug, Error)]
39-
#[error("Failed to load translations")]
4039
pub enum LoadError {
41-
Io(#[from] std::io::Error),
42-
Deserialize(#[from] serde_json::Error),
43-
InvalidLocale(#[from] ParserError),
44-
InvalidFileName(Utf8PathBuf),
40+
#[error("Failed to load translation directory {path:?}")]
41+
ReadDir {
42+
path: Utf8PathBuf,
43+
#[source]
44+
source: std::io::Error,
45+
},
46+
47+
#[error("Failed to read translation file {path:?}")]
48+
ReadFile {
49+
path: Utf8PathBuf,
50+
#[source]
51+
source: std::io::Error,
52+
},
53+
54+
#[error("Failed to deserialize translation file {path:?}")]
55+
Deserialize {
56+
path: Utf8PathBuf,
57+
#[source]
58+
source: serde_json::Error,
59+
},
60+
61+
#[error("Invalid locale for file {path:?}")]
62+
InvalidLocale {
63+
path: Utf8PathBuf,
64+
#[source]
65+
source: ParserError,
66+
},
67+
68+
#[error("Invalid file name {path:?}")]
69+
InvalidFileName { path: Utf8PathBuf },
4570
}
4671

4772
/// A translator for a set of translations.
@@ -90,18 +115,36 @@ impl Translator {
90115
pub fn load_from_path(path: &Utf8Path) -> Result<Self, LoadError> {
91116
let mut translations = HashMap::new();
92117

93-
let dir = path.read_dir_utf8()?;
118+
let dir = path.read_dir_utf8().map_err(|source| LoadError::ReadDir {
119+
path: path.to_owned(),
120+
source,
121+
})?;
122+
94123
for entry in dir {
95-
let entry = entry?;
124+
let entry = entry.map_err(|source| LoadError::ReadDir {
125+
path: path.to_owned(),
126+
source,
127+
})?;
96128
let path = entry.into_path();
97129
let Some(name) = path.file_stem() else {
98-
return Err(LoadError::InvalidFileName(path));
130+
return Err(LoadError::InvalidFileName { path });
131+
};
132+
133+
let locale: Locale = match Locale::from_str(name) {
134+
Ok(locale) => locale,
135+
Err(source) => return Err(LoadError::InvalidLocale { path, source }),
99136
};
100137

101-
let locale: Locale = Locale::from_str(name)?;
138+
let mut file = match File::open(&path) {
139+
Ok(file) => file,
140+
Err(source) => return Err(LoadError::ReadFile { path, source }),
141+
};
142+
143+
let content = match serde_json::from_reader(&mut file) {
144+
Ok(content) => content,
145+
Err(source) => return Err(LoadError::Deserialize { path, source }),
146+
};
102147

103-
let mut file = File::open(path)?;
104-
let content = serde_json::from_reader(&mut file)?;
105148
translations.insert(locale.into(), content);
106149
}
107150

0 commit comments

Comments
 (0)