In this lesson, you will learn how to create your own error types to make your code's failure states more descriptive and easier to handle.
Why Custom Errors?
So far, you’ve used Result<T, E> with standard types like String or &str for errors. While that works, it’s not very specific. If you’re building a library, you want your users to know exactly what went wrong—like "File Missing" versus "Permission Denied"—without having to parse a string.
In Rust, the idiomatic way to define custom errors is by using an enum.
Building a Domain-Specific Error
Imagine you are building a tool to parse a configuration file. You might encounter two specific problems: the file is missing, or the format is invalid. We can represent this with an enum:
enum ConfigError {
FileNotFound,
InvalidFormat,
}
By defining this enum, you create a formal "vocabulary" for your application's failures. You can now use this as the second type parameter in your Result.
Integration with Result
When you write functions that might fail, you return a Result using your custom enum instead of a generic string:
fn load_config() -> Result<String, ConfigError> {
let success = false;
if success {
Ok("Settings loaded".to_string())
} else {
Err(ConfigError::FileNotFound)
}
}
Now, when a user calls your function, they can use match to handle the specific variants of your ConfigError. This is much safer than checking if a string contains certain words:
match load_config() {
Ok(data) => println!("Success: {}", data),
Err(ConfigError::FileNotFound) => println!("Please check your path."),
Err(ConfigError::InvalidFormat) => println!("Check your file syntax."),
}
By creating custom error enums, you take advantage of Rust's powerful pattern matching to ensure your error handling logic is exhaustive and robust. You aren't just saying "something went wrong"; you are categorizing exactly which part of your domain failed.
Key Takeaway: Use enums to define custom error types so you can handle specific failure scenarios with pattern matching instead of relying on ambiguous strings.