liveBook · Manning

Error

As explained in Rust Servers, Services, and Apps

The Error trait is a Rust standard-library trait for types that represent and describe errors.

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

How Rust Servers, Services, and Apps covers it

How deep it goes
Builds a custom enum with Debug, Error, Display, and mapping, then stops short of broader error-design patterns.
Examples
Demonstrates MyError, file operations, integer parsing, and an Actix /hello handler.
What it assumes
Assumes familiarity with Result, match, ? propagation, and basic Rust functions.
What you can do after
Apply it via custom error types and propagate failures through Actix handlers with ?.
How it connects
Connects Error with Result, the ? operator, Display, From, Actix Web, and HTTP responses.

Also explained in

Compare how 3 books explain Error →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust Servers, Services, and Apps. The section links point to the parts of the book it draws on.