diff --git a/src/main.rs b/src/main.rs index 3e6bf66..aff7d2a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -55,7 +55,13 @@ fn get_saved_locale() -> Option { fn get_saved_json(preferences: &serde_json::Value) -> serde_json::Value { let save_path = fix_path(preferences["save_path"].as_str().unwrap()); if Path::new(&save_path).exists() { - read_json(save_path.as_str()) + match read_json(save_path.as_str()) { + Ok(v) => v, + Err(e) => { + error!("Could not load saved settings from {save_path}: {e}"); + json!({"locale": ""}) + }, + } } else { json!({"locale": ""}) } @@ -265,7 +271,9 @@ fn on_link1_clicked(param: &[glib::Value]) -> Option { fn on_delete_window(_param: &[glib::Value]) -> Option { let saved_json = &*G_SAVE_JSON.lock().unwrap(); let preferences = unsafe { G_HELLO_WINDOW.as_ref().unwrap().get_preferences("save_path") }; - write_json(preferences.as_str().unwrap(), saved_json); + if let Err(e) = write_json(preferences.as_str().unwrap(), saved_json) { + error!("Could not save settings: {e}"); + } Some(false.to_value()) } diff --git a/src/utils.rs b/src/utils.rs index 33534ce..ee06e15 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -26,16 +26,17 @@ pub fn fix_path(path: &str) -> String { } #[inline] -pub fn read_json(path: &str) -> serde_json::Value { +pub fn read_json(path: &str) -> anyhow::Result { let buf = fix_path(path); - let data = fs::read_to_string(buf).expect("Unable to read file"); - serde_json::from_str(&data).expect("Unable to parse") + let data = fs::read_to_string(buf)?; + Ok(serde_json::from_str(&data)?) } #[inline] -pub fn write_json(path: &str, content: &serde_json::Value) { - let output = File::create(fix_path(path)).expect("Unable to open file for writing"); - serde_json::to_writer(output, content).expect("Unable to write json to file"); +pub fn write_json(path: &str, content: &serde_json::Value) -> anyhow::Result<()> { + let output = File::create(fix_path(path))?; + serde_json::to_writer(output, content)?; + Ok(()) } #[inline]