FAQ - Help and questions

What should my app do when its settings file is missing or damaged?

#settings#errors#reliability#desktoppublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A missing file is normal on the first run, so start with defaults and say nothing. A damaged file is different: move it aside to a backup name before the next save overwrites it, tell the user, and start with defaults. Never panic on startup because of a settings file. The example was compiled and run.

Checked with rustc 1.93.0, Windows 11, serde 1.x, serde_json 1.x; compiled and run, in a temporary folder that the program removes.

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Reading settings can fail in three different ways, and they deserve three different reactions:

SituationHow to detect itReaction
The file does not existio::ErrorKind::NotFoundFirst run. Use defaults, no message.
The file cannot be read (permissions, in use)another io::ErrorUse defaults, tell the user once, and do not overwrite the file.
The file is read but is not validthe parser's errorMove 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.

src/main.rsrust
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();
}
text
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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet