Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.79 KB | None | 0 0
  1. use failure::{Context, Fail};
  2. use failure::ResultExt;
  3.  
  4. /// Extension methods for failure `Result`.
  5. pub trait ResultContext<T, E> {
  6. /// Wraps the error type in a context type generated by looking at the
  7. /// error value. This is very similar to `with_context` but much more
  8. /// concise.
  9. fn ctx(self, s: &str) -> Result<T, Context<String>>;
  10. }
  11.  
  12. impl<T, E> ResultContext<T, E> for Result<T, E> where E: Fail {
  13. fn ctx(self, s: &str) -> Result<T, Context<String>> {
  14. self.map_err(|failure| {
  15. let context = format!("{}: {}", s, failure);
  16. failure.context(context)
  17. })
  18. }
  19. }
  20.  
  21. pub fn foo() -> Result<i32, failure::Error> {
  22. Ok(5i32)
  23. }
  24.  
  25. pub fn main() -> Result<(), failure::Error> {
  26. // This works.
  27. let _ = foo().with_context(|_| "foo".to_string())?;
  28. // This doesn't.
  29. foo().ctx("foo")?
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement