Guest User

Untitled

a guest
Dec 14th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. use std::error::Error;
  2.  
  3. pub struct ChainError {
  4. line: u32,
  5. file: &'static str,
  6. desc: String,
  7. error_cause: Option<Box<dyn Error + 'static>>,
  8. }
  9.  
  10. impl Error for ChainError {
  11. fn description(&self) -> &str {
  12. &self.desc
  13. }
  14.  
  15. fn source(&self) -> Option<&(dyn Error + 'static)> {
  16. if let Some(ref e) = self.error_cause {
  17. Some(e.as_ref())
  18. } else {
  19. None
  20. }
  21. }
  22. }
  23.  
  24. impl ::std::fmt::Display for ChainError {
  25. fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
  26. writeln!(f, "{}", self.desc)?;
  27. if let Some(e) = self.source() {
  28. writeln!(f, "\nCaused by:")?;
  29. ::std::fmt::Display::fmt(&e, f)?;
  30. }
  31. Ok(())
  32. }
  33. }
  34.  
  35. impl ::std::fmt::Debug for ChainError {
  36. fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
  37. writeln!(f, "{}:{}: {}", self.file, self.line, self.desc)?;
  38. if let Some(e) = self.source() {
  39. writeln!(f, "\nCaused by:")?;
  40. ::std::fmt::Debug::fmt(&e, f)?;
  41. }
  42. Ok(())
  43. }
  44. }
  45.  
  46. #[macro_export]
  47. macro_rules! chain_error {
  48. ($r:expr, $v:expr) => {
  49. $r.map_err(|e| ChainError {
  50. line: line!(),
  51. file: file!(),
  52. desc: $v,
  53. error_cause: Some(e.into()),
  54. })
  55. };
  56. }
  57.  
  58. fn throw_error() -> Result<(), ChainError> {
  59. let directory = String::from("ldfhgdfkgjdf");
  60. chain_error!(
  61. ::std::fs::remove_dir(&directory),
  62. format!("Could not remove directory '{}'!", &directory)
  63. )?;
  64. Ok(())
  65. }
  66.  
  67. fn main() -> Result<(), ChainError> {
  68. let res = chain_error!(throw_error(), "I has an error.".into());
  69.  
  70. if let Err(ref my_err) = res {
  71. println!("Display Error:");
  72. println!("==============");
  73. println!("{}", my_err);
  74. println!("-----------\n");
  75. println!("Debug Error:");
  76. println!("==============");
  77. println!("{:?}", my_err);
  78. println!("-----------");
  79. };
  80. res
  81. }
Add Comment
Please, Sign In to add comment