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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
use self::KindPriv::*;

use std::error;
use std::fmt;
use http::StatusCode;

/// Builder for Error objects.
#[derive(Debug)]
pub struct Builder {
    kind: Option<(String, String)>,
    detail: Option<String>,
    status: Option<StatusCode>,
}

/// Errors that can happen inside Tower Web.
/// The object of this type is serializable into "Problem Detail" as defined in RFC7807.
#[derive(Serialize)]
pub struct Error {
    #[serde(rename = "type")]
    kind: String,
    title: String,
    // NOTE: type of this property might be changed in the future.
    // Nevertheless, String type should be accepted.
    #[serde(skip_serializing_if = "Option::is_none")]
    detail: Option<String>,
    #[serde(skip)]
    status: StatusCode,

    // TODO: this property isn't used and should be removed
    #[serde(skip)]
    error_kind: ErrorKind,
}

// ===== impl Builder =====

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 {
            kind: self.kind,
            detail: self.detail,
            status: Some(status),

        }
    }

    /// 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())),
            detail: self.detail,
            status: self.status,
        }
    }

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

    /// 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),
                (Some(_), None) => Error::from(StatusCode::INTERNAL_SERVER_ERROR),
                (None, Some(status)) => Error::from(status),
                (None, None) => Error::from(StatusCode::INTERNAL_SERVER_ERROR),
            };

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

// ===== impl Error =====

impl Error {
    // TODO: this function should return '&self.kind' property
    // and its return value should be changed to '&str'
    /// Returns the corresponding `ErrorKind` for this error.
    #[deprecated(note="return value of the function will be changed to &str")]
    pub fn kind(&self) -> &ErrorKind {
        &self.error_kind
    }

    /// 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,
            status,

            // TODO: this property isn't used and should be removed
            error_kind: ErrorKind::new(&status),
        }
    }

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

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

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

impl error::Error for Error {
    fn description(&self) -> &str {
        self.status_code().canonical_reason().unwrap_or("Unknown status code")
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("Error")
            .field("kind", &self.kind)
            .field("title", &self.title)
            .field("detail", &self.detail)
            .field("status", &self.status)
            .finish()
    }
}

impl fmt::Display for Error {
    #[allow(deprecated)] // .cause() is deprecated on nightly
    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)?;
        }

        use std::error::Error;
        if let Some(ref cause) = self.cause() {
            write!(fmt, ": {}", cause)?;
        }

        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,
            status,

            // TODO: this property isn't used and should be removed
            error_kind: ErrorKind::new(&status),
        }
    }
}

// Obsolete

/// A list specifying the general categories of Tower Web errors.
pub struct ErrorKind {
    kind: KindPriv,
}

#[derive(Debug, Eq, PartialEq, Clone, Copy)]
enum KindPriv {
    BadRequest,
    Unauthorized,
    Fordidden,
    NotFound,
    UnprocessableEntity,
    Internal,
}

impl From<ErrorKind> for Error {
    fn from(error_kind: ErrorKind) -> Error {
        error_kind.status_code().into()
    }
}

// ===== impl ErrorKind =====

impl ErrorKind {
    /// Returns a new `ErrorKind` value representing a 400 -- bad request error.
    #[deprecated(note="please use 'Error::from(http::StatusCode::BAD_REQUEST)' instead")]
    pub fn bad_request() -> ErrorKind {
        ErrorKind { kind: BadRequest }
    }

    /// Returns `true` if `self` represents a 400 -- bad request error
    #[deprecated(note="please use 'kind() == http::StatusCode::BAD_REQUEST' instead")]
    pub fn is_bad_request(&self) -> bool {
        self.kind == BadRequest
    }

    /// Returns a new `ErrorKind` value representing a 401 -- unauthorized error.
    #[deprecated(note="please use 'Error::from(http::StatusCode::UNAUTHORIZED)' instead")]
    pub fn unauthorized() -> ErrorKind {
        ErrorKind { kind: Unauthorized }
    }

    /// Returns a new `ErrorKind` value representing a 403 -- forbidden error.
    #[deprecated(note="please use 'Error::from(http::StatusCode::FORBIDDEN)' instead")]
    pub fn forbidden() -> ErrorKind {
        ErrorKind { kind: Fordidden }
    }

    /// Returns a new `ErrorKind` value representing a 404 -- not found error
    #[deprecated(note="please use 'Error::from(http::StatusCode::NOT_FOUND)' instead")]
    pub fn not_found() -> ErrorKind {
        ErrorKind { kind: NotFound }
    }

    /// Returns `true` if `self` represents a 404 -- not found error
    #[deprecated(note="please use 'kind() == http::StatusCode::NOT_FOUND' instead")]
    pub fn is_not_found(&self) -> bool {
        self.kind == NotFound
    }

    /// Returns a new `ErrorKind` value representing a 422 -- unprocessable entity error
    #[deprecated(note="please use 'Error::from(http::StatusCode::UNPROCESSABLE_ENTITY)' instead")]
    pub fn unprocessable_entity() -> ErrorKind {
        ErrorKind { kind: UnprocessableEntity }
    }

    /// Returns a new `ErrorKind` value representing 500 -- internal server
    /// error.
    #[deprecated(note="please use 'Error::from(http::StatusCode::INTERNAL_SERVER_ERROR)' instead")]
    pub fn internal() -> ErrorKind {
        ErrorKind { kind: Internal }
    }

    /// Returns `true` if `self` represents a 500 -- internal server error.
    #[deprecated(note="please use 'kind() == http::StatusCode::INTERNAL_SERVER_ERROR' instead")]
    pub fn is_internal(&self) -> bool {
        self.kind == Internal
    }

    fn status_code(&self) -> StatusCode {
        match self.kind {
            BadRequest => StatusCode::BAD_REQUEST,
            Unauthorized => StatusCode::UNAUTHORIZED,
            Fordidden => StatusCode::FORBIDDEN,
            NotFound => StatusCode::NOT_FOUND,
            UnprocessableEntity => StatusCode::UNPROCESSABLE_ENTITY,
            Internal => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }

    fn new(status: &StatusCode) -> Self {
        match status {
            &StatusCode::BAD_REQUEST => ErrorKind {
                kind: BadRequest
            },
            &StatusCode::UNAUTHORIZED => ErrorKind {
                kind: Unauthorized
            },
            &StatusCode::FORBIDDEN => ErrorKind {
                kind: Fordidden
            },
            &StatusCode::NOT_FOUND => ErrorKind {
                kind: NotFound
            },
            &StatusCode::UNPROCESSABLE_ENTITY => ErrorKind {
                kind: UnprocessableEntity
            },
            _ => ErrorKind {
                kind: Internal
            },
        }
    }
}

impl fmt::Debug for ErrorKind {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self.kind {
            BadRequest => "ErrorKind::BadRequest",
            Unauthorized => "ErrorKind::Unauthorized",
            Fordidden => "ErrorKind::Forbidden",
            NotFound => "ErrorKind::NotFound",
            UnprocessableEntity => "ErrorKind::UnprocessableEntity",
            Internal => "ErrorKind::Internal",
        }.fmt(fmt)
    }
}