chainerror/booksrc/tutorial7.md

36 lines
1.1 KiB
Markdown
Raw Normal View History

2018-12-20 16:37:08 +01:00
# The root cause of all Errors
2018-12-20 15:14:21 +01:00
2018-12-21 13:50:08 +01:00
`chainerror` also has some helper methods:
~~~rust,ignore
fn is_chain<T: 'static + Display + Debug>(&self) -> bool
fn downcast_chain_ref<T: 'static + Display + Debug>(&self) -> Option<&ChainError<T>>
fn downcast_chain_mut<T: 'static + Display + Debug>(&mut self) -> Option<&mut ChainError<T>>
fn root_cause(&self) -> Option<&(dyn Error + 'static)>
fn find_cause<U: Error + 'static>(&self) -> Option<&U>
fn find_chain_cause<U: Error + 'static>(&self) -> Option<&ChainError<U>>
fn kind<'a>(&'a self) -> &'a T
~~~
Using `downcast_chain_ref::<String>()` gives a `ChainError<String>`, which can be used
to call `.find_cause::<io::Error>()`.
~~~rust,ignore
if let Some(s) = e.downcast_chain_ref::<String>() {
if let Some(ioerror) = s.find_cause::<io::Error>() {
~~~
or to use `.root_cause()`, which of course can be of any type implementing `std::error::Error`.
~~~rust,ignore
if let Some(e) = s.root_cause() {
~~~
2018-12-20 15:14:21 +01:00
2018-12-20 14:52:06 +01:00
~~~rust
use crate::chainerror::*;
{{#include ../examples/tutorial7.rs:2:}}
# #[allow(dead_code)]
# mod chainerror {
{{#includecomment ../src/lib.rs}}
# }
~~~