RRust By Example

Custom Error Type

Define custom error types with thiserror or manually.

Custom Error Type

Define custom error types with thiserror or manually.

Difficulty

Advanced

Code

rust
use std::fmt;
use std::num::ParseIntError;

#[derive(Debug)]
enum AppError {
    Parse(ParseIntError),
    Validation(String),
}

impl fmt::Display for AppError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            AppError::Parse(e) => write!(f, "Parse error: {}", e),
            AppError::Validation(msg) => write!(f, "Validation: {}", msg),
        }
    }
}

impl From<ParseIntError> for AppError {
    fn from(e: ParseIntError) -> Self {
        AppError::Parse(e)
    }
}

fn parse_positive(input: &str) -> Result<u32, AppError> {
    let n: u32 = input.parse()?;
    if n == 0 {
        return Err(AppError::Validation("must be positive".into()));
    }
    Ok(n)
}

fn main() {
    println!("{:?}", parse_positive("42"));
    println!("{:?}", parse_positive("0"));
    println!("{:?}", parse_positive("abc"));
}

Explanation

This example demonstrates how to use custom error type in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the error-handling category to build a complete understanding of this topic.

More Error Handling Examples