From 57240aa00d7a8f7cd611654c44bd04cec9192133 Mon Sep 17 00:00:00 2001 From: Daniel Date: Fri, 12 Nov 2021 16:02:32 +0100 Subject: Better error handling, less .unwraps() Some of these unwraps are fine to stay, mostly those that deal with locks - in this case, crashing the program if something goes wrong is probably fine. However, we also had a lot of other places where we panic'd on errors, even though we really shouldn't have. For example, an invalid zip file would bring down the whole scanner. In this case, we now use proper Result<>s and we log the error. Some places stay with unwrap() for now, mainly the code that is rare and obvious when it goes wrong - such as an overflow in input values. It could be made nicer, but it is not a priority for now. Some unwraps() have been changed to expect() to signal why they shouldn't fail. --- src/guilds.rs | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) (limited to 'src/guilds.rs') diff --git a/src/guilds.rs b/src/guilds.rs index e847841..115de42 100644 --- a/src/guilds.rs +++ b/src/guilds.rs @@ -5,6 +5,8 @@ use std::collections::HashMap; use std::fs::File; use std::sync::RwLock; +use anyhow::Result; +use log::{error, warn}; use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; @@ -51,19 +53,31 @@ pub fn lookup(api_id: &str) -> Option { /// Loads the cache from the file system. pub fn prepare_cache() { let path = paths::cache_path(); - if !path.is_file() { - return; - } + if let Some(path) = path { + if !path.is_file() { + return; + } - let file = File::open(path).expect("Unable to read cache file"); - let cache = serde_json::from_reader(file).expect("Cache file has invalid format"); - let mut target = CACHE.write().unwrap(); - *target = cache; + let file = File::open(path).expect("Unable to read cache file"); + let cache = serde_json::from_reader(file).expect("Cache file has invalid format"); + let mut target = CACHE.write().unwrap(); + *target = cache; + } else { + warn!("Could not determine the cache path, the persistent guild cache is disabled"); + } } /// Saves the cache to the file system pub fn save_cache() { let path = paths::cache_path(); - let file = File::create(path).expect("Cannot open cache for writing"); - serde_json::to_writer(file, &*CACHE.read().unwrap()).unwrap(); + // We already warned about that earlier + if let Some(path) = path { + let result: Result<()> = try { + let file = File::create(path)?; + serde_json::to_writer(file, &*CACHE.read().unwrap())?; + }; + if let Err(e) = result { + error!("Error saving the cache: {}", e); + } + } } -- cgit v1.2.3