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 theResulttype from theanyhowcrate, 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 validi32value or an error. -
if y == 0 { return Err(anyhow!("Division by zero")); }- This checks ifyis equal to zero, and if it is, it returns an error using theanyhow!macro. -
Ok(x / y)- Ifyis not equal to zero, this will return the result of the division as anOkvalue.
Helpful links:
More of Rust
- How to use regex lookahead in Rust?
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to replace strings using Rust regex?
- How to split a string with Rust regex?
- How to replace all matches using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to use negation in Rust regex?
- How to perform matrix operations in Rust?
- How to match a URL with a regex in Rust?
See more codes...