The std::error::Error trait identifies types that represent and describe errors. Implementing it lets custom errors participate in Rust error propagation and Actix Web conversion. section 5.2
Custom errors in an Actix handler
Define a MyError enum for parsing and I/O failures, derive Debug, implement std::error::Error and Display, then return Result<i32, MyError>. In an Actix handler, errors such as std::io::Error can propagate with ?, convert into actix_web::error::Error, and become HTTP responses. section 5.2
use std::fmt;
use std::fs::File;
use std::io::Write;
#[derive(Debug)]
pub enum MyError { #1
ParseError,
IOError,
}
impl std::error::Error for MyError {} #2
impl fmt::Display for MyError { #3
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
MyError::ParseError => write!(f, "Parse Error"),
MyError::IOError => write!(f, "IO Error"),
}
}
}
fn main() {
let result = square("INVALID");
match result { #4
Ok(res) => println!("Result is {:?}",res),
Err(e) => println!("Error in parsing: {:?}",e)
};
}
fn square(val: &str) -> Result<i32, MyError> {
let num = val.parse::<i32>().map_err(|_| MyError::ParseError)?; #5
let mut f = File::open("fictionalfile.txt").map_err(
|_| MyError::IOError)?; #5
let string_to_write = format!("Square of {:?} is {:?}", num, i32::pow(
num, 2));
f.write_all(string_to_write.as_bytes())
.map_err(|_| MyError::IOError)?; #5
Ok(i32::pow(num, 2))
}
Inspect a complete custom error enum with Error and Display implementations, explicit error mapping, and Result matching. section 5.2


