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
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use http::StatusCode;
use serde_derive::Serialize;
use std::{collections::HashMap, error, fmt};

/// Configure and build an error.
#[derive(Debug)]
pub struct Builder {
    kind: Option<(String, String)>,
    detail: Option<String>,
    status: Option<StatusCode>,
}

/// Error object.
#[derive(Clone, Debug, Serialize)]
pub struct Error {
    #[serde(rename = "type")]
    kind: String,
    title: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    detail: Option<String>,
    #[serde(skip)]
    status: StatusCode,
    #[serde(skip)]
    extras: HashMap<String, String>,
}

impl Builder {
    fn new() -> Self {
        Self {
            kind: None,
            detail: None,
            status: None,
        }
    }

    /// Set status of the error.
    pub fn status(self, status: StatusCode) -> Self {
        Self {
            status: Some(status),
            ..self
        }
    }

    /// Set kind and title of the error.
    pub fn kind(self, kind: &str, title: &str) -> Self {
        Self {
            kind: Some((kind.to_owned(), title.to_owned())),
            ..self
        }
    }

    /// Set detailed information about the error.
    pub fn detail(self, detail: &str) -> Self {
        Self {
            detail: Some(detail.to_owned()),
            ..self
        }
    }

    /// Create an error object.
    pub fn build(self) -> Error {
        let mut err = match (self.kind, self.status) {
            (Some((ref kind, ref title)), Some(status)) => Error::new(kind, title, status),
            (None, Some(status)) => Error::from(status),
            _ => Error::from(StatusCode::INTERNAL_SERVER_ERROR),
        };

        match self.detail {
            Some(ref detail) => {
                err.set_detail(detail);
                err
            }
            None => err,
        }
    }
}

impl Error {
    /// Create an error object.
    pub fn new(kind: &str, title: &str, status: StatusCode) -> Self {
        Self {
            kind: kind.to_owned(),
            title: title.to_owned(),
            detail: None,
            extras: HashMap::new(),
            status,
        }
    }

    /// Set kind and title of the error.
    pub fn set_kind(&mut self, kind: &str, title: &str) -> &mut Self {
        self.kind = kind.to_owned();
        self.title = title.to_owned();
        self
    }

    /// Return a kind for this error.
    pub fn kind(&self) -> &str {
        &self.kind
    }

    /// Return a title for this error.
    pub fn title(&self) -> &str {
        &self.title
    }

    /// Set a status code information about the error.
    pub fn set_status_code(&mut self, value: StatusCode) -> &mut Self {
        self.status = value;
        self
    }

    /// Return a status code for this error.
    pub fn status_code(&self) -> StatusCode {
        self.status
    }

    /// Return a detail for this error.
    pub fn detail(&self) -> Option<&str> {
        self.detail.as_ref().map(|s| s.as_str())
    }

    /// Set detailed information about the error.
    pub fn set_detail(&mut self, value: &str) -> &mut Self {
        self.detail = Some(value.to_owned());
        self
    }

    /// Return all extras for this error.
    pub fn extras(&self) -> &HashMap<String, String> {
        &self.extras
    }

    /// Set detailed information about the error.
    pub fn set_extra(&mut self, key: &str, value: &str) -> &mut Self {
        self.extras.insert(key.to_owned(), value.to_owned());
        self
    }

    /// Create an error builder object.
    pub fn builder() -> Builder {
        Builder::new()
    }
}

impl error::Error for Error {}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "[{}] {}", self.kind, self.title)?;

        if let Some(ref detail) = self.detail {
            write!(fmt, ": {}", detail)?;
        }

        Ok(())
    }
}

impl From<StatusCode> for Error {
    fn from(status: StatusCode) -> Self {
        let title = status.canonical_reason().unwrap_or("Unknown status code");
        Self {
            kind: String::from("about:blank"),
            title: title.to_owned(),
            detail: None,
            extras: HashMap::new(),
            status,
        }
    }
}