Rust: Error Handling with Custom Types
Error handling is a vital component in any programming paradigm. Rust, being a systems programming language, places a significant emphasis on robust and type-safe error handling. In this article, we’ll explore how to define custom error types in Rust and handle them in idiomatic ways.
Defining Custom Errors
Rust provides the std::error::Error
trait, which can be implemented for types that you want to use as errors. By convention, Rust errors also implement the Display
trait for human-readable error messages.
In the provided code, we have two custom error types: FileError
and ParseError
.
#[derive(Debug)]
enum FileError {
NotFound,
PermissionDenied,
}
impl Display for FileError {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
match self {
FileError::NotFound => write!(f, "File not found"),
FileError::PermissionDenied => write!(f, "Permission denied"),
}
}
}
impl std::error::Error for FileError {}
The FileError
type is an enumeration with two variants: NotFound
and PermissionDenied
. Implementing the Display
trait allows us to provide a custom string representation for each variant. We also implement the Error
trait for FileError
, signaling that it can be used as an error type.