Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::error::Error;
- pub struct ChainError {
- line: u32,
- file: &'static str,
- desc: String,
- error_cause: Option<Box<dyn Error + 'static>>,
- }
- impl Error for ChainError {
- fn description(&self) -> &str {
- &self.desc
- }
- fn source(&self) -> Option<&(dyn Error + 'static)> {
- if let Some(ref e) = self.error_cause {
- Some(e.as_ref())
- } else {
- None
- }
- }
- }
- impl ::std::fmt::Display for ChainError {
- fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
- writeln!(f, "{}", self.desc)?;
- if let Some(e) = self.source() {
- writeln!(f, "\nCaused by:")?;
- ::std::fmt::Display::fmt(&e, f)?;
- }
- Ok(())
- }
- }
- impl ::std::fmt::Debug for ChainError {
- fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
- writeln!(f, "{}:{}: {}", self.file, self.line, self.desc)?;
- if let Some(e) = self.source() {
- writeln!(f, "\nCaused by:")?;
- ::std::fmt::Debug::fmt(&e, f)?;
- }
- Ok(())
- }
- }
- #[macro_export]
- macro_rules! chain_error {
- ($r:expr, $v:expr) => {
- $r.map_err(|e| ChainError {
- line: line!(),
- file: file!(),
- desc: $v,
- error_cause: Some(e.into()),
- })
- };
- }
- fn throw_error() -> Result<(), ChainError> {
- let directory = String::from("ldfhgdfkgjdf");
- chain_error!(
- ::std::fs::remove_dir(&directory),
- format!("Could not remove directory '{}'!", &directory)
- )?;
- Ok(())
- }
- fn main() -> Result<(), ChainError> {
- let res = chain_error!(throw_error(), "I has an error.".into());
- if let Err(ref my_err) = res {
- println!("Display Error:");
- println!("==============");
- println!("{}", my_err);
- println!("-----------\n");
- println!("Debug Error:");
- println!("==============");
- println!("{:?}", my_err);
- println!("-----------");
- };
- res
- }
Add Comment
Please, Sign In to add comment