How to Create Custom Error Types in Rust

Create a custom error enum in Rust and implement Display and Error traits to define specific application failure modes.

Define a custom error type using an enum and implement the std::fmt::Display and std::error::Error traits to handle it gracefully.

use std::fmt;
use std::io;

#[derive(Debug)]
enum AppError {
    Io(io::Error),
    NotFound(String),
}

impl fmt::Display for AppError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            AppError::Io(e) => write!(f, "IO error: {}", e),
            AppError::NotFound(msg) => write!(f, "Item not found: {}", msg),
        }
    }
}

impl std::error::Error for AppError {}

fn main() -> Result<(), AppError> {
    // Example usage
    Err(AppError::NotFound("user".to_string()))
}