navid/veins / impl-rust / veins-rust/src/error.rs
error.rs
← veins-rust/src · 1180 bytes · raw · download
use std::fmt;
use std::io;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub struct Error {
message: String,
}
impl Error {
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
}
}
pub fn context(self, context: impl AsRef<str>) -> Self {
Self::new(format!("{}: {}", context.as_ref(), self.message))
}
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.message)
}
}
impl std::error::Error for Error {}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Self {
Self::new(error.to_string())
}
}
impl From<String> for Error {
fn from(message: String) -> Self {
Self::new(message)
}
}
impl From<&str> for Error {
fn from(message: &str) -> Self {
Self::new(message)
}
}
pub trait OptionExt<T> {
fn or_error(self, message: impl Into<String>) -> Result<T>;
}
impl<T> OptionExt<T> for Option<T> {
fn or_error(self, message: impl Into<String>) -> Result<T> {
self.ok_or_else(|| Error::new(message))
}
}