chainerror/booksrc/tutorial2.md

32 lines
975 B
Markdown
Raw Normal View History

2018-12-20 16:37:08 +01:00
# Simple Chained String Errors
2018-12-20 15:14:21 +01:00
2018-12-21 13:50:08 +01:00
With relatively small changes and the help of the `cherr!` macro of the `chainerror` crate
the `String` errors are now chained together.
2018-12-20 15:14:21 +01:00
Press the play button in the upper right corner and see the nice debug output.
2018-12-20 14:52:06 +01:00
~~~rust
2019-03-04 11:38:35 +01:00
{{#include ../examples/tutorial2.rs}}
2018-12-20 14:52:06 +01:00
# #[allow(dead_code)]
# mod chainerror {
{{#includecomment ../src/lib.rs}}
# }
2018-12-20 15:14:21 +01:00
~~~
### What did we do here?
~~~rust,ignore
2018-12-21 13:50:08 +01:00
{{#include ../examples/tutorial2.rs:13:15}}
2018-12-20 15:14:21 +01:00
~~~
2018-12-21 13:50:08 +01:00
The macro `cherr!(olderror, newerror)` stores `olderror` as the source/cause of `newerror`
along with the filename (`file!()`) and line number (`line!()`)
and returns `newerror`.
2018-12-20 15:14:21 +01:00
2018-12-21 13:50:08 +01:00
`Err()?` then returns the inner error applying `.into()`, so that we
2018-12-20 15:14:21 +01:00
again have a `Err(Box<Error>)` as a result.
The `Debug` implementation of `ChainError<T>` (which is returned by `cherr!()`)
prints the `Debug` of `T` prefixed with the stored filename and line number.
2018-12-21 13:50:08 +01:00
`ChainError<T>` in our case is `ChainError<String>`.