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
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
Define custom error types with enums and Display/Error traits.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the error-handling category to build a complete understanding of this topic.