0
0
Rustprogramming~10 mins

Custom error types in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Custom error types
Define struct or enum for error
Implement std::fmt::Display
Implement std::error::Error
Use error type in functions
Return Result<T, CustomError>
Handle error with match or ? operator
End
Create a custom error type by defining a struct or enum, implement Display and Error traits, then use it in functions returning Result to handle errors clearly.
Execution Sample
Rust
use std::fmt;

#[derive(Debug)]
enum MyError {
    NotFound,
    InvalidInput(String),
}

impl fmt::Display for MyError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            MyError::NotFound => write!(f, "Item not found"),
            MyError::InvalidInput(msg) => write!(f, "Invalid input: {}", msg),
        }
    }
}

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

fn find_item(id: i32) -> Result<String, MyError> {
    if id == 0 {
        Err(MyError::NotFound)
    } else if id < 0 {
        Err(MyError::InvalidInput("negative id".to_string()))
    } else {
        Ok("Item found".to_string())
    }
}

fn main() {
    match find_item(-1) {
        Ok(item) => println!("{}", item),
        Err(e) => println!("Error: {}", e),
    }
}
Defines a custom error enum with two variants, implements Display and Error traits, then uses it in a function returning Result to handle errors.
Execution Table
StepCode LineActionVariable/StateOutput/Result
1Define enum MyErrorCreate custom error type with variants NotFound and InvalidInputMyError enum defined
2Implement Display for MyErrorDefine how error messages are shownDisplay trait implemented
3Implement Error for MyErrorMark MyError as an error typeError trait implemented
4Call find_item(-1)Start function with id = -1id = -1
5Check if id == 0Condition falseid = -1
6Check if id < 0Condition trueid = -1Return Err(MyError::InvalidInput("negative id"))
7Match in main on ResultErr branch takene = InvalidInput("negative id")Print: Error: Invalid input: negative id
8Program endsNo more code
💡 Function returns Err variant because id < 0 condition is true, main prints error message and program ends.
Variable Tracker
VariableStartAfter Step 4After Step 6Final
idundefined-1-1-1
Result from find_itemundefinedpendingErr(MyError::InvalidInput("negative id"))Err(MyError::InvalidInput("negative id"))
e (error in main)undefinedundefinedInvalidInput("negative id")InvalidInput("negative id")
Key Moments - 3 Insights
Why do we implement the Display trait for the custom error?
Implementing Display lets us define the error message shown when printing the error, as seen in execution_table step 7 where the error message is printed.
What happens if the function returns Err? How is it handled?
When find_item returns Err (step 6), main matches on the Result and takes the Err branch (step 7), printing the error message instead of panicking.
Why use an enum for custom errors instead of just a struct?
An enum lets us represent different kinds of errors in one type, like NotFound and InvalidInput, making error handling clearer and more flexible (step 1).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 6. What error variant is returned by find_item(-1)?
AMyError::InvalidInput("negative id")
BMyError::NotFound
COk("Item found")
DNone
💡 Hint
Check the 'Output/Result' column at step 6 in the execution_table.
At which step does the main function print the error message?
AStep 5
BStep 7
CStep 4
DStep 8
💡 Hint
Look for the step where 'Print: Error: Invalid input: negative id' appears in the execution_table.
If find_item was called with id = 0, what would be the returned error variant?
AOk("Item found")
BMyError::InvalidInput("negative id")
CMyError::NotFound
DNo error
💡 Hint
Refer to the condition checks in the code and execution_table steps 5 and 6.
Concept Snapshot
Define a custom error type using enum or struct.
Implement fmt::Display to show error messages.
Implement std::error::Error to mark it as an error.
Use Result<T, CustomError> in functions.
Handle errors with match or ? operator.
Full Transcript
This example shows how to create custom error types in Rust. We define an enum MyError with variants NotFound and InvalidInput. We implement the Display trait to control how error messages appear when printed. We also implement the Error trait to mark MyError as a proper error type. The function find_item returns a Result with our custom error. It returns Err with NotFound if id is zero, Err with InvalidInput if id is negative, or Ok if id is positive. In main, we call find_item with -1, which triggers the InvalidInput error. We match on the Result and print the error message. This step-by-step trace shows how variables change and how errors flow through the program.