Reputation: 1825
Given two functions like these:
fn foo() -> Result<i32, Box<dyn std::error::Error>> {
// returns an error if something goes wrong
}
fn bar() -> Result<bool, Box<dyn std::error::Error>> {
let x = foo(); // could be ok or err
if x.is_err() {
return // I want to return whatever error occured in function foo
}
}
Is it possible to return the exact error that appeared in function foo
from function bar
?
Also notice, the Result<T, E>
enum has different T
in these functions
Upvotes: 1
Views: 2262
Reputation: 16805
I would just let the ? operator do all the work.
fn foo(a: i32) -> Result<i32, Box<dyn std::error::Error>> {
if a < 10 {
// returns an error if something goes wrong
Err(Box::from("bad value"))
} else {
Ok(a + 2)
}
}
fn bar(a: i32) -> Result<bool, Box<dyn std::error::Error>> {
let x = foo(a)?;
Ok(x > 5)
}
fn main() {
println!("{:?}", bar(2)); // displays Err("bad value")
println!("{:?}", bar(12)); // displays Ok(true)
}
Upvotes: 6