Skip to content

Instantly share code, notes, and snippets.

@staticgc
Last active February 26, 2021 03:53
Show Gist options
  • Save staticgc/9246d7b340e4a57f9bf39472f0a98082 to your computer and use it in GitHub Desktop.
Save staticgc/9246d7b340e4a57f9bf39472f0a98082 to your computer and use it in GitHub Desktop.
Clonable Error in Rust
use std::sync::Arc;
#[derive(Clone, Debug)]
pub enum Error {
pub kind: Arc<ErrorKind>,
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match *self.kind {
// Return the external error as source
ErrorKind::IO(ref err) => Some(err),
// All native errors to this crate have no external source, hence return None
ErrorKind::InvalidInput(_) => None
}
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.kind.fmt(f)
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Error {
Error{kind: Arc::new(kind)}
}
}
//----------------------------------------------------------
// ErrorKind ...
//----------------------------------------------------------
pub enum ErrorKind {
IO(std::io::Error), // Example of wrapping an external error
InvalidInput(String), // Error native to *this* crate
}
impl std::fmt::Display for ErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ErrorKind::IO(err) => write!(f, "{}", err),
ErrorKind::InvalidInput(input) => write!(f, "Invalid input: {}", input)
}
}
}
impl std::fmt::Debug for ErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&format!("{}", self))
}
}
// Convert std::io::Error to Error
impl From<std::io::Error> for Error {
fn from(err: std::io::Error) -> Error {
Error{kind: Arc::new(ErrorKind::IO(err))}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment