1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
use std::fmt; pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; #[derive(Debug)] pub struct Error { msg: String, cause: Option<Box<dyn std::error::Error>> } impl Error { pub fn new(msg: &str) -> Error { Error { msg: msg.into(), cause: None } } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { self.cause.as_ref().map(Box::as_ref) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.msg)?; if let Some(cause) = &self.cause { write!(f, "\n\tcaused by: {}", cause)?; } Ok(()) } } pub trait ErrorExt { fn wrap(self, msg: &str) -> Error; } impl<T: Into<Box<dyn std::error::Error>>> ErrorExt for T { fn wrap(self, msg: &str) -> Error { Error { msg: msg.into(), cause: Some(self.into()) } } } pub trait ResultExt<T> { fn wrap_err(self, msg: &str) -> std::result::Result<T, Error>; } impl<T, E: ErrorExt> ResultExt<T> for std::result::Result<T, E> { fn wrap_err(self, msg: &str) -> std::result::Result<T, Error> { self.map_err(|err| err.wrap(msg)) } }