Rust Custom Error Type
Define custom error types with the thiserror crate pattern.
error-handlingpatterns
rust
use std::fmt;
#[derive(Debug)]
pub enum AppError {
NotFound(String),
Unauthorized,
Database(String),
Validation(Vec<String>),
}
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AppError::NotFound(msg) => write!(f, "Not found: {msg}"),
AppError::Unauthorized => write!(f, "Unauthorized"),
AppError::Database(msg) => write!(f, "Database error: {msg}"),
AppError::Validation(errs) => write!(f, "Validation: {}", errs.join(", ")),
}
}
}
impl std::error::Error for AppError {}