use anyhow::Result;
fn main() -> Result<(), Box<dyn Error>> {
match try {
let n = might_error()?;
} {
Ok(_) => { eprintln!("Everything fine"); },
Err(_) => { eprintln!("Calculation failed"); },
}
}
fn might_error() -> Result<u32> {
Ok(0)
}
But I'm getting:
error[E0282]: type annotations needed
--> src\main.rs:25:24
|
25 | let n = might_error()?;
| ^ cannot infer type of error for `?` operator
|
= note: `?` implicitly converts the error value into a type implementing `From<anyhow::Error>`
Yes, the question mark operator will always insert an error conversion via the From trait. Since the output error type is not fixed in any way, it is unable to figure out what the error type should be.
If your actual code doesn't need the error details, you could try going through Option, which doesn't need annotations because it doesn't involve From (anymore).
Something like
match try {
let n = might_error().ok()?;
Response::text("Calculation complete")
} {
Some(resp) => resp,
None => Response::text("Calculation failed").with_status_code(500),
}