Created
April 4, 2020 18:35
-
-
Save vasilakisfil/5a74f36914e0704b7d0c2e4a7835ed20 to your computer and use it in GitHub Desktop.
basic error structure in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::{error::Error as StdError, fmt}; | |
#[derive(Debug)] | |
pub struct Error { | |
pub kind: ErrorKind, | |
pub context: ErrorContext, | |
} | |
#[derive(Debug)] | |
pub enum ErrorKind { | |
Empty, | |
Custom(String) | |
} | |
#[derive(Debug)] | |
pub enum ErrorContext { | |
Empty, | |
} | |
impl fmt::Display for ErrorKind { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
match self { | |
ErrorKind::Custom(ref inner) => write!(f, "error: {}", inner), | |
_ => write!(f, "unknown error, {:?}", self), | |
} | |
} | |
} | |
impl fmt::Display for Error { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
match self.context { | |
ErrorContext::Empty => write!(f, "{}", self.kind), | |
_ => write!(f, "unknown error ({:?})", self), | |
} | |
} | |
} | |
impl StdError for Error {} | |
impl<E> From<E> for Error | |
where | |
E: Into<ErrorKind>, | |
{ | |
fn from(e: E) -> Self { | |
Error { | |
context: ErrorContext::Empty, | |
kind: e.into(), | |
} | |
} | |
} | |
impl From<String> for ErrorKind { | |
fn from(e: String) -> Self { | |
ErrorKind::Custom(e) | |
} | |
} | |
impl From<&str> for ErrorKind { | |
fn from(e: &str) -> Self { | |
ErrorKind::Custom(e.into()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment