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
65
66
67
use base64::DecodeError;
use serde_json;
use std::error;
use std::fmt;
use std::string::FromUtf8Error;
use openssl::error::ErrorStack;

#[derive(Debug)]
pub enum Error {
    /// Custom, Medallion specific errors.
    Custom(String),
    /// String encoding errors.
    Utf8(FromUtf8Error),
    /// Base64 encoding or decoding errors.
    Base64(DecodeError),
    /// JSON parsing or stringifying errors.
    JSON(serde_json::Error),
    /// Errors from RSA operations.
    Crypto(ErrorStack),
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::Custom(ref message) => message,
            Error::Utf8(ref err) => err.description(),
            Error::Base64(ref err) => err.description(),
            Error::JSON(ref err) => err.description(),
            Error::Crypto(ref err) => err.description(),
        }
    }

    fn cause(&self) -> Option<&error::Error> {
        match *self {
            Error::Custom(_) => None,
            Error::Utf8(ref err) => Some(err),
            Error::Base64(ref err) => Some(err),
            Error::JSON(ref err) => Some(err),
            Error::Crypto(ref err) => Some(err),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::Custom(ref message) => f.write_str(message),
            Error::Utf8(ref err) => err.fmt(f),
            Error::Base64(ref err) => err.fmt(f),
            Error::JSON(ref err) => err.fmt(f),
            Error::Crypto(ref err) => err.fmt(f),
        }
    }
}

macro_rules! error_wrap {
    ($f: ty, $e: expr) => {
        impl From<$f> for Error {
            fn from(f: $f) -> Error { $e(f) }
        }
    }
}

error_wrap!(FromUtf8Error, Error::Utf8);
error_wrap!(DecodeError, Error::Base64);
error_wrap!(serde_json::Error, Error::JSON);
error_wrap!(ErrorStack, Error::Crypto);