Welcome to the Rust tutorial on thiserror! In this lesson, we'll explore the thiserror crate, which makes it easy to create custom error types with detailed error messages in Rust. Let's get started!
thiserror?thiserror is a popular Rust crate that helps in creating custom error types with informative error messages. It's a valuable tool for writing more robust, readable, and maintainable code.
š Note: A crate is a package of Rust code, similar to libraries in other programming languages.
thiserrorTo use thiserror, first, add it as a dependency in your Cargo.toml file:
[dependencies]
thiserror = "1.0"Next, run cargo build or cargo run to install the crate.
Now let's create a custom error type using thiserror.
use thiserror::Error;
#[derive(Debug, Error)]
enum CalculatorError {
/// Division by zero error
#[error("Cannot divide by zero")]
DivByZero,
/// Overflow error
#[error("Number is too large to be represented")]
Overflow,
}In this example, we created a CalculatorError enum with two variants: DivByZero and Overflow. By using the derive macro, we generated useful traits like Debug and Error for our custom error type.
š” Pro Tip: Use descriptive error messages to help debug and understand the issue when errors occur.
Now, let's create a function that can return our custom error:
fn divide(a: i32, b: i32) -> Result<i32, CalculatorError> {
if b == 0 {
return Err(CalculatorError::DivByZero);
}
Ok(a / b)
}In this function, we're using Rust's built-in Result type to handle our custom error. If the divisor is zero, we return an error; otherwise, we return the result of the division.
Now, let's use our custom error in a real-world example:
fn main() {
let result = divide(10, 2);
match result {
Ok(r) => println!("Result: {}", r),
Err(e) => println!("Error: {}", e),
}
}In this example, we call the divide function and use a match statement to handle both the Ok and Err cases. If the division is successful, we print the result; otherwise, we print the error message.
šÆ Here's a quick quiz to test your understanding:
What is the purpose of the `thiserror` crate in Rust?
That's it for our introduction to thiserror! In the next tutorial, we'll dive deeper into using thiserror for more complex scenarios and explore advanced features. Happy coding! š