Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
basic error structure in Rust
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