Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use failure::{Context, Fail};
- use failure::ResultExt;
- /// Extension methods for failure `Result`.
- pub trait ResultContext<T, E> {
- /// Wraps the error type in a context type generated by looking at the
- /// error value. This is very similar to `with_context` but much more
- /// concise.
- fn ctx(self, s: &str) -> Result<T, Context<String>>;
- }
- impl<T, E> ResultContext<T, E> for Result<T, E> where E: Fail {
- fn ctx(self, s: &str) -> Result<T, Context<String>> {
- self.map_err(|failure| {
- let context = format!("{}: {}", s, failure);
- failure.context(context)
- })
- }
- }
- pub fn foo() -> Result<i32, failure::Error> {
- Ok(5i32)
- }
- pub fn main() -> Result<(), failure::Error> {
- // This works.
- let _ = foo().with_context(|_| "foo".to_string())?;
- // This doesn't.
- foo().ctx("foo")?
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement