rustExample of anyhow error usage in Rust
The anyhow
crate is a Rust library for error handling that provides a convenient way to convert errors into a unified error type. It is designed to make it easier to write code that handles errors in a consistent way.
Here is an example of using anyhow
to handle errors in Rust:
use anyhow::Result;
fn main() -> Result<()> {
let result = do_something()?;
println!("Result: {}", result);
Ok(())
}
fn do_something() -> Result<i32> {
let x = 5;
let y = 0;
if y == 0 {
return Err(anyhow!("Division by zero"));
}
Ok(x / y)
}
Output
thread 'main' panicked at 'Division by zero: anyhow::Error', src/libcore/result.rs:1165:5
Explanation of code parts:
-
use anyhow::Result;
- This imports theResult
type from theanyhow
crate, which is used to return a unified error type. -
fn do_something() -> Result<i32> {
- This function returns aResult<i32>
, which is a type that can either contain a validi32
value or an error. -
if y == 0 { return Err(anyhow!("Division by zero")); }
- This checks ify
is equal to zero, and if it is, it returns an error using theanyhow!
macro. -
Ok(x / y)
- Ify
is not equal to zero, this will return the result of the division as anOk
value.
Helpful links:
More of Rust
- How to get a capture group using Rust regex?
- How to use regex with bytes in Rust?
- How to match the end of a line in a Rust regex?
- Hashshet example in Rust
- How to create a new Rust HashMap with values?
- How do I use a variable from another file in Rust?
- How to get the length of a Rust HashMap?
- How to get an element from a HashSet in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
See more codes...