I find myself implementing application-specific error and result types in Rust quite often. Here is my standard template for future reference:
use std::sync::Arc; | |
#[allow(dead_code)] | |
pub type Result<T> = std::result::Result<T, Error>; | |
#[derive(Debug, Clone)] | |
#[allow(dead_code)] | |
pub enum Error { | |
General(&'static str), | |
IO(Arc<std::io::Error>), | |
} | |
impl std::fmt::Display for Error { | |
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { | |
match self { | |
Error::General(message) => write!(f, "General({})", message), | |
Error::IO(error) => write!(f, "IO({})", error), | |
} | |
} | |
} | |
impl std::error::Error for Error { | |
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { | |
match self { | |
Error::General(_) => None, | |
Error::IO(error) => Some(error.as_ref()), | |
} | |
} | |
} | |
impl std::convert::From<std::io::Error> for Error { | |
fn from(error: std::io::Error) -> Self { | |
Error::IO(Arc::new(error)) | |
} | |
} |
Content © 2025 Richard Cook. All rights reserved.