Custom error types help you describe problems in your program clearly. They make it easier to find and fix mistakes.
0
0
Custom error types in Rust
Introduction
When you want to explain specific problems in your code.
When you need to handle different errors in different ways.
When you want to give helpful messages to users or developers.
When you want to organize errors neatly in your program.
Syntax
Rust
enum MyError { NotFound, InvalidInput(String), ConnectionFailed, }
Use enum to list all possible errors.
You can add extra information inside errors using parentheses.
Examples
This error type shows two simple errors: file not found and no permission.
Rust
enum FileError {
NotFound,
PermissionDenied,
}This error type includes a message for invalid format and a simple empty input error.
Rust
enum ParseError { InvalidFormat(String), EmptyInput, }
This error type has a general
Other case with a message for unexpected errors.Rust
enum NetworkError { Timeout, Disconnected, Other(String), }
Sample Program
This program defines a custom error type MyError with two cases. It checks numbers and returns errors if the number is zero or negative. The main function shows how errors print friendly messages.
Rust
use std::fmt; // Define a custom error type enum MyError { NotFound, InvalidInput(String), } // Implement Display to show error messages 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), } } } // A function that returns a Result with our custom error fn check_value(value: i32) -> Result<(), MyError> { if value < 0 { Err(MyError::InvalidInput("negative number".to_string())) } else if value == 0 { Err(MyError::NotFound) } else { Ok(()) } } fn main() { let values = [10, 0, -5]; for &v in &values { match check_value(v) { Ok(()) => println!("Value {} is okay", v), Err(e) => println!("Error for value {}: {}", v, e), } } }
OutputSuccess
Important Notes
Implementing Display helps show clear error messages.
Use Result<T, E> to return success or your custom error.
Custom errors make your code easier to understand and fix.
Summary
Custom error types describe specific problems in your program.
Use enums to list different errors with optional extra details.
Implement Display to show friendly messages when errors happen.