From 4535477b09ff1753cdc83e3c44585ad393a5c716 Mon Sep 17 00:00:00 2001 From: Teddy Wing Date: Fri, 22 Apr 2016 17:20:27 -0400 Subject: Write alias errors to STDERR instead of panicking We use an `.ok()` call on the result of the write so that we can ignore these errors. I think we shouldn't really worry too much about not being to write to STDERR, and instead try to print out the full email message as best we can. In order to write the error (`e.to_string()`), we needed to implement `fmt::Display` on `AliasSearchError`. While I was at it also implemented the `error::Error` trait. --- src/main.rs | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/src/main.rs b/src/main.rs index e5bab05..1be35a1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,6 @@ +use std::error; use std::io::{self, BufRead, BufReader, Write}; +use std::fmt; use std::fs::{File, OpenOptions}; use std::path::Path; @@ -78,8 +80,32 @@ enum AliasSearchError { Io(io::Error), } -// impl fmt::Display for AliasSearchError {} -// impl error::Error for AliasSearchError {} +impl fmt::Display for AliasSearchError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + AliasSearchError::NotFound => write!(f, ""), + AliasSearchError::EmailExists => write!(f, ""), + AliasSearchError::Io(ref err) => write!(f, "IO error: {}", err), + } + } +} + +impl error::Error for AliasSearchError { + fn description(&self) -> &str { + match *self { + AliasSearchError::NotFound => "Alias could not be found in aliases file", + AliasSearchError::EmailExists => "Email already exists in aliases file", + AliasSearchError::Io(ref err) => err.description(), + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + AliasSearchError::Io(ref err) => Some(err), + _ => None, + } + } +} impl From for AliasSearchError { fn from(err: io::Error) -> AliasSearchError { @@ -144,7 +170,7 @@ fn main() { match write_alias(line) { Ok(_) => continue, Err(AliasSearchError::NotFound) | Err(AliasSearchError::EmailExists) => continue, - Err(e) => panic!(e), + Err(e) => io::stderr().write(e.to_string().as_bytes()).ok(), }; } } -- cgit v1.2.3