Boilerplate for Rust error/result

2020-03-27

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))
}
}
view raw error.rs hosted with ❤ by GitHub

Related posts

String conversions in Rust follow-up
String conversions in Rust
Bracket pattern in Rust
Parsing MSBuild project XML in Rust
Traits and polymorphism in Rust
Richard’s Workspace Tool - more Rust programming

Tags

Rust
Programming

Content © 2025 Richard Cook. All rights reserved.