parent
614d246747
commit
9a25b48b49
@ -0,0 +1,57 @@
|
||||
//! The Rear error wrapper
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt::{Display, Formatter, Result as FmtResult};
|
||||
use std::result::Result as StdResult;
|
||||
|
||||
/// A `std::result::Result` wrapper that simply has a `Rear` as the error.
|
||||
pub type Result<T> = StdResult<T, Rear>;
|
||||
|
||||
/// A `Rear` is simply a message paired with the error.
|
||||
#[derive(Debug)]
|
||||
pub struct Rear {
|
||||
error: Box<dyn Error>,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl Rear {
|
||||
/// Return a reference to the error.
|
||||
pub fn error(&self) -> &Box<dyn Error> {
|
||||
&self.error
|
||||
}
|
||||
|
||||
/// Return the message as a `&str`.
|
||||
pub fn message(&self) -> &str {
|
||||
&self.message
|
||||
}
|
||||
|
||||
/// Create a new `Rear` from an error implementing `std::error::Error` with
|
||||
/// a message from anything that implementes `Into<String>`.
|
||||
pub fn new<S: Into<String>>(error: Box<dyn Error>, message: S) -> Self {
|
||||
let message = message.into();
|
||||
|
||||
Self {
|
||||
error,
|
||||
message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Rear {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
|
||||
if ! self.message.is_empty() {
|
||||
write!(f, "{}", self.error)
|
||||
} else {
|
||||
write!(f, "{}\n{}", &self.message, &self.error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Box<dyn Error>> for Rear {
|
||||
fn from(error: Box<dyn Error>) -> Self {
|
||||
Self {
|
||||
error: error,
|
||||
message: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in new issue