From 325f53e6d444db638608edcea8e03cf171434cc2 Mon Sep 17 00:00:00 2001 From: Abraham Toriz Date: Fri, 23 Jul 2021 20:01:43 -0500 Subject: [PATCH] improve errors for IO --- src/config.rs | 20 ++++++++++++++++---- src/error.rs | 15 +++++++++++---- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/src/config.rs b/src/config.rs index fbd97f6..9152a9d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -117,9 +117,15 @@ impl Config { let path: PathBuf = path.as_ref().into(); let mut contents = String::new(); - let mut file = File::open(&path).map_err(|_| FileNotFound(path.clone()))?; + let mut file = File::open(&path).map_err(|e| CouldntReadConfigFile { + path: path.clone(), + error: e, + })?; - file.read_to_string(&mut contents).map_err(|_| CouldntRead(path.clone()))?; + file.read_to_string(&mut contents).map_err(|e| CouldntReadConfigFile { + path: path.clone(), + error: e, + })?; serde_yaml::from_str(&contents).map_err(|error| YamlError { path, error @@ -130,9 +136,15 @@ impl Config { let path: PathBuf = path.as_ref().into(); let mut contents = String::new(); - let mut file = File::open(&path).map_err(|_| FileNotFound(path.clone()))?; + let mut file = File::open(&path).map_err(|e| CouldntReadConfigFile { + path: path.clone(), + error: e, + })?; - file.read_to_string(&mut contents).map_err(|_| CouldntRead(path.clone()))?; + file.read_to_string(&mut contents).map_err(|e| CouldntReadConfigFile { + path: path.clone(), + error: e, + })?; toml::from_str(&contents).map_err(|error| TomlError { path, error diff --git a/src/error.rs b/src/error.rs index 5158368..d66d3a6 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,5 +1,6 @@ use std::result; use std::path::PathBuf; +use std::io; use thiserror::Error; use chrono::NaiveDateTime; @@ -15,11 +16,17 @@ pub enum Error { #[error("Could not find home directory or a place where configuration can be read an written :(")] NoHomeDir, - #[error("The file {0} was not found")] - FileNotFound(PathBuf), + #[error("Could not read the config file at - #[error("Error reading the file: {0}")] - CouldntRead(PathBuf), +{path} + +with error: + +{error}")] + CouldntReadConfigFile { + path: PathBuf, + error: io::Error, + }, #[error("Couldn't parse toml file at: {path}\nwith error: {error}")] TomlError{ path: PathBuf, error: toml::de::Error},