~james/gengo

gengo/samples-test/samples/Rust/error.rs -rw-r--r-- 1.4 KiB
50871857 — james chore(import): snapshot james.dad.town/gengo at 8f775550b0ee 16 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use std::error::Error as ErrorTrait;
use std::fmt;

macro_rules! error_kind {
    ($($name:ident, $message:literal),*) => {
        /// The kind of error that occurred.
        #[derive(Debug)]
        #[non_exhaustive]
        pub enum ErrorKind {
            $(
                $name,
            )*
        }

        impl fmt::Display for ErrorKind {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                match self {
                    $(
                        Self::$name => write!(f, $message),
                    )*
                }
            }
        }
    };
}

error_kind!(NoRepository, "no repository found");

impl ErrorTrait for ErrorKind {}

#[derive(Debug)]
pub struct Error {
    kind: ErrorKind,
    source: Option<Box<dyn ErrorTrait>>,
}

impl Error {
    pub fn new(kind: ErrorKind) -> Self {
        Self { kind, source: None }
    }

    pub fn with_source(kind: ErrorKind, source: impl ErrorTrait + 'static) -> Self {
        Self {
            kind,
            source: Some(Box::new(source)),
        }
    }

    pub fn kind(&self) -> &ErrorKind {
        &self.kind
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", &self.kind)
    }
}

impl ErrorTrait for Error {
    fn source(&self) -> Option<&(dyn ErrorTrait + 'static)> {
        self.source.as_ref().map(|s| s.as_ref())
    }
}