Answer#
Reading settings can fail in three different ways, and they deserve three different reactions:
| Situation | How to detect it | Reaction |
|---|---|---|
| The file does not exist | io::ErrorKind::NotFound | First run. Use defaults, no message. |
| The file cannot be read (permissions, in use) | another io::Error | Use defaults, tell the user once, and do not overwrite the file. |
| The file is read but is not valid | the parser's error | Move the file to a backup name, tell the user, use defaults. |
The third case is the one that loses data if handled badly. If you fall back to defaults and save later, the broken file is replaced, and with it any chance of recovering what was in it.
use serde::Deserialize;
use std::fs;
use std::path::Path;
#[derive(Deserialize, Debug, Default)]
struct Settings {
font_size: Option<u32>,
}
fn load_or_default(path: &Path) -> Settings {
let text = match fs::read_to_string(path) {
Ok(t) => t,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Settings::default(), // normal on first run
Err(e) => {
eprintln!("cannot read settings: {e}");
return Settings::default();
}
};
match serde_json::from_str(&text) {
Ok(s) => s,
Err(e) => {
// Keep the damaged file for the user instead of overwriting it on the next save.
let backup = path.with_extension("json.bad");
let _ = fs::rename(path, &backup);
eprintln!("settings file is damaged ({e}); moved to {}", backup.file_name().unwrap().to_string_lossy());
Settings::default()
}
}
}
fn main() {
let dir = std::env::temp_dir().join("rs-forum-corrupt-demo");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("settings.json");
println!("missing: {:?}", load_or_default(&path));
fs::write(&path, "{ \"font_size\": 1").unwrap(); // cut off, as after a crash
println!("damaged: {:?}", load_or_default(&path));
println!("backup exists: {}", dir.join("settings.json.bad").exists());
fs::remove_dir_all(&dir).unwrap();
}missing: Settings { font_size: None }
settings file is damaged (EOF while parsing an object at line 1 column 16); moved to settings.json.bad
damaged: Settings { font_size: None }
backup exists: true(The second line is printed to standard error, so it can appear in a different order from the others when both go to the same console.)
In a GUI app, replace eprintln! with a visible message, for example a banner "Your settings could not be read. A copy was kept as settings.json.bad." The next save then writes a clean file.
Common mistakes#
unwrap()on the load. One bad byte makes the app unable to start, and users cannot fix a file they do not know about.- Treating every error as "file missing". You would then overwrite files that were only temporarily locked.
- Writing the settings file non-atomically, which is how files get damaged in the first place; see the thread on saving safely.
Related questions#
Should I validate the values too?#
Yes. A valid JSON file can say font_size: 0. Clamp numbers to a sensible range after loading.
Sources#
- std::io::ErrorKind: https://doc.rust-lang.org/std/io/enum.ErrorKind.html (read 2026-12-05)