chainerror/booksrc/tutorial9.md

34 lines
865 B
Markdown
Raw Normal View History

2018-12-20 16:37:08 +01:00
# Selective Error Handling
2018-12-20 15:14:21 +01:00
2018-12-21 13:50:08 +01:00
What about functions returning different Error types?
In this example `func1()` can return either `Func1ErrorFunc2` or `Func1ErrorIO`.
We might want to `match` on `func1()` with something like:
~~~rust,ignore
fn main() -> Result<(), Box<Error>> {
match func1() {
Err(e) if let Some(s) = e.downcast_chain_ref::<Func1ErrorIO>() =>
eprintln!("Func1ErrorIO:\n{:?}", s),
Err(e) if let Some(s) = e.downcast_chain_ref::<Func1ErrorFunc2>() =>
eprintln!("Func1ErrorFunc2:\n{:?}", s),
Ok(_) => {},
}
Ok(())
}
~~~
but this is not valid rust code, so we end up doing it the hard way.
In the next chapter, we will see, how to solve this more elegantly.
2018-12-20 15:14:21 +01:00
2018-12-20 14:52:06 +01:00
~~~rust
2019-03-04 11:38:35 +01:00
{{#include ../examples/tutorial9.rs}}
2018-12-20 14:52:06 +01:00
# #[allow(dead_code)]
# mod chainerror {
{{#includecomment ../src/lib.rs}}
# }
2018-12-21 13:50:08 +01:00
~~~