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
use std::{cell::RefCell, fmt, io::Write as _};

use actix_http::{body::Body, header, StatusCode};
use bytes::{BufMut as _, BytesMut};

use crate::{Error, HttpRequest, HttpResponse, Responder, ResponseError};

/// Wraps errors to alter the generated response status code.
///
/// In following example, the `io::Error` is wrapped into `ErrorBadRequest` which will generate a
/// response with the 400 Bad Request status code instead of the usual status code generated by
/// an `io::Error`.
///
/// # Examples
/// ```
/// # use std::io;
/// # use actix_web::{error, HttpRequest};
/// async fn handler_error() -> Result<String, actix_web::Error> {
///     let err = io::Error::new(io::ErrorKind::Other, "error");
///     Err(error::ErrorBadRequest(err))
/// }
/// ```
pub struct InternalError<T> {
    cause: T,
    status: InternalErrorType,
}

enum InternalErrorType {
    Status(StatusCode),
    Response(RefCell<Option<HttpResponse>>),
}

impl<T> InternalError<T> {
    /// Constructs an `InternalError` with given status code.
    pub fn new(cause: T, status: StatusCode) -> Self {
        InternalError {
            cause,
            status: InternalErrorType::Status(status),
        }
    }

    /// Constructs an `InternalError` with pre-defined response.
    pub fn from_response(cause: T, response: HttpResponse) -> Self {
        InternalError {
            cause,
            status: InternalErrorType::Response(RefCell::new(Some(response))),
        }
    }
}

impl<T: fmt::Debug> fmt::Debug for InternalError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.cause.fmt(f)
    }
}

impl<T: fmt::Display> fmt::Display for InternalError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.cause.fmt(f)
    }
}

impl<T> ResponseError for InternalError<T>
where
    T: fmt::Debug + fmt::Display,
{
    fn status_code(&self) -> StatusCode {
        match self.status {
            InternalErrorType::Status(st) => st,
            InternalErrorType::Response(ref resp) => {
                if let Some(resp) = resp.borrow().as_ref() {
                    resp.head().status
                } else {
                    StatusCode::INTERNAL_SERVER_ERROR
                }
            }
        }
    }

    fn error_response(&self) -> HttpResponse {
        match self.status {
            InternalErrorType::Status(status) => {
                let mut res = HttpResponse::new(status);
                let mut buf = BytesMut::new().writer();
                let _ = write!(buf, "{}", self);

                res.headers_mut().insert(
                    header::CONTENT_TYPE,
                    header::HeaderValue::from_static("text/plain; charset=utf-8"),
                );
                res.set_body(Body::from(buf.into_inner()))
            }

            InternalErrorType::Response(ref resp) => {
                if let Some(resp) = resp.borrow_mut().take() {
                    resp
                } else {
                    HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR)
                }
            }
        }
    }
}

impl<T> Responder for InternalError<T>
where
    T: fmt::Debug + fmt::Display + 'static,
{
    fn respond_to(self, _: &HttpRequest) -> HttpResponse {
        HttpResponse::from_error(self)
    }
}

macro_rules! error_helper {
    ($name:ident, $status:ident) => {
        paste::paste! {
            #[doc = "Helper function that wraps any error and generates a `" $status "` response."]
            #[allow(non_snake_case)]
            pub fn $name<T>(err: T) -> Error
            where
                T: fmt::Debug + fmt::Display + 'static,
            {
                InternalError::new(err, StatusCode::$status).into()
            }
        }
    }
}

error_helper!(ErrorBadRequest, BAD_REQUEST);
error_helper!(ErrorUnauthorized, UNAUTHORIZED);
error_helper!(ErrorPaymentRequired, PAYMENT_REQUIRED);
error_helper!(ErrorForbidden, FORBIDDEN);
error_helper!(ErrorNotFound, NOT_FOUND);
error_helper!(ErrorMethodNotAllowed, METHOD_NOT_ALLOWED);
error_helper!(ErrorNotAcceptable, NOT_ACCEPTABLE);
error_helper!(
    ErrorProxyAuthenticationRequired,
    PROXY_AUTHENTICATION_REQUIRED
);
error_helper!(ErrorRequestTimeout, REQUEST_TIMEOUT);
error_helper!(ErrorConflict, CONFLICT);
error_helper!(ErrorGone, GONE);
error_helper!(ErrorLengthRequired, LENGTH_REQUIRED);
error_helper!(ErrorPayloadTooLarge, PAYLOAD_TOO_LARGE);
error_helper!(ErrorUriTooLong, URI_TOO_LONG);
error_helper!(ErrorUnsupportedMediaType, UNSUPPORTED_MEDIA_TYPE);
error_helper!(ErrorRangeNotSatisfiable, RANGE_NOT_SATISFIABLE);
error_helper!(ErrorImATeapot, IM_A_TEAPOT);
error_helper!(ErrorMisdirectedRequest, MISDIRECTED_REQUEST);
error_helper!(ErrorUnprocessableEntity, UNPROCESSABLE_ENTITY);
error_helper!(ErrorLocked, LOCKED);
error_helper!(ErrorFailedDependency, FAILED_DEPENDENCY);
error_helper!(ErrorUpgradeRequired, UPGRADE_REQUIRED);
error_helper!(ErrorPreconditionFailed, PRECONDITION_FAILED);
error_helper!(ErrorPreconditionRequired, PRECONDITION_REQUIRED);
error_helper!(ErrorTooManyRequests, TOO_MANY_REQUESTS);
error_helper!(
    ErrorRequestHeaderFieldsTooLarge,
    REQUEST_HEADER_FIELDS_TOO_LARGE
);
error_helper!(
    ErrorUnavailableForLegalReasons,
    UNAVAILABLE_FOR_LEGAL_REASONS
);
error_helper!(ErrorExpectationFailed, EXPECTATION_FAILED);
error_helper!(ErrorInternalServerError, INTERNAL_SERVER_ERROR);
error_helper!(ErrorNotImplemented, NOT_IMPLEMENTED);
error_helper!(ErrorBadGateway, BAD_GATEWAY);
error_helper!(ErrorServiceUnavailable, SERVICE_UNAVAILABLE);
error_helper!(ErrorGatewayTimeout, GATEWAY_TIMEOUT);
error_helper!(ErrorHttpVersionNotSupported, HTTP_VERSION_NOT_SUPPORTED);
error_helper!(ErrorVariantAlsoNegotiates, VARIANT_ALSO_NEGOTIATES);
error_helper!(ErrorInsufficientStorage, INSUFFICIENT_STORAGE);
error_helper!(ErrorLoopDetected, LOOP_DETECTED);
error_helper!(ErrorNotExtended, NOT_EXTENDED);
error_helper!(
    ErrorNetworkAuthenticationRequired,
    NETWORK_AUTHENTICATION_REQUIRED
);

#[cfg(test)]
mod tests {
    use actix_http::error::ParseError;

    use super::*;

    #[test]
    fn test_internal_error() {
        let err = InternalError::from_response(ParseError::Method, HttpResponse::Ok().finish());
        let resp: HttpResponse = err.error_response();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[test]
    fn test_error_helpers() {
        let res: HttpResponse = ErrorBadRequest("err").into();
        assert_eq!(res.status(), StatusCode::BAD_REQUEST);

        let res: HttpResponse = ErrorUnauthorized("err").into();
        assert_eq!(res.status(), StatusCode::UNAUTHORIZED);

        let res: HttpResponse = ErrorPaymentRequired("err").into();
        assert_eq!(res.status(), StatusCode::PAYMENT_REQUIRED);

        let res: HttpResponse = ErrorForbidden("err").into();
        assert_eq!(res.status(), StatusCode::FORBIDDEN);

        let res: HttpResponse = ErrorNotFound("err").into();
        assert_eq!(res.status(), StatusCode::NOT_FOUND);

        let res: HttpResponse = ErrorMethodNotAllowed("err").into();
        assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);

        let res: HttpResponse = ErrorNotAcceptable("err").into();
        assert_eq!(res.status(), StatusCode::NOT_ACCEPTABLE);

        let res: HttpResponse = ErrorProxyAuthenticationRequired("err").into();
        assert_eq!(res.status(), StatusCode::PROXY_AUTHENTICATION_REQUIRED);

        let res: HttpResponse = ErrorRequestTimeout("err").into();
        assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);

        let res: HttpResponse = ErrorConflict("err").into();
        assert_eq!(res.status(), StatusCode::CONFLICT);

        let res: HttpResponse = ErrorGone("err").into();
        assert_eq!(res.status(), StatusCode::GONE);

        let res: HttpResponse = ErrorLengthRequired("err").into();
        assert_eq!(res.status(), StatusCode::LENGTH_REQUIRED);

        let res: HttpResponse = ErrorPreconditionFailed("err").into();
        assert_eq!(res.status(), StatusCode::PRECONDITION_FAILED);

        let res: HttpResponse = ErrorPayloadTooLarge("err").into();
        assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);

        let res: HttpResponse = ErrorUriTooLong("err").into();
        assert_eq!(res.status(), StatusCode::URI_TOO_LONG);

        let res: HttpResponse = ErrorUnsupportedMediaType("err").into();
        assert_eq!(res.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);

        let res: HttpResponse = ErrorRangeNotSatisfiable("err").into();
        assert_eq!(res.status(), StatusCode::RANGE_NOT_SATISFIABLE);

        let res: HttpResponse = ErrorExpectationFailed("err").into();
        assert_eq!(res.status(), StatusCode::EXPECTATION_FAILED);

        let res: HttpResponse = ErrorImATeapot("err").into();
        assert_eq!(res.status(), StatusCode::IM_A_TEAPOT);

        let res: HttpResponse = ErrorMisdirectedRequest("err").into();
        assert_eq!(res.status(), StatusCode::MISDIRECTED_REQUEST);

        let res: HttpResponse = ErrorUnprocessableEntity("err").into();
        assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);

        let res: HttpResponse = ErrorLocked("err").into();
        assert_eq!(res.status(), StatusCode::LOCKED);

        let res: HttpResponse = ErrorFailedDependency("err").into();
        assert_eq!(res.status(), StatusCode::FAILED_DEPENDENCY);

        let res: HttpResponse = ErrorUpgradeRequired("err").into();
        assert_eq!(res.status(), StatusCode::UPGRADE_REQUIRED);

        let res: HttpResponse = ErrorPreconditionRequired("err").into();
        assert_eq!(res.status(), StatusCode::PRECONDITION_REQUIRED);

        let res: HttpResponse = ErrorTooManyRequests("err").into();
        assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS);

        let res: HttpResponse = ErrorRequestHeaderFieldsTooLarge("err").into();
        assert_eq!(res.status(), StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE);

        let res: HttpResponse = ErrorUnavailableForLegalReasons("err").into();
        assert_eq!(res.status(), StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS);

        let res: HttpResponse = ErrorInternalServerError("err").into();
        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);

        let res: HttpResponse = ErrorNotImplemented("err").into();
        assert_eq!(res.status(), StatusCode::NOT_IMPLEMENTED);

        let res: HttpResponse = ErrorBadGateway("err").into();
        assert_eq!(res.status(), StatusCode::BAD_GATEWAY);

        let res: HttpResponse = ErrorServiceUnavailable("err").into();
        assert_eq!(res.status(), StatusCode::SERVICE_UNAVAILABLE);

        let res: HttpResponse = ErrorGatewayTimeout("err").into();
        assert_eq!(res.status(), StatusCode::GATEWAY_TIMEOUT);

        let res: HttpResponse = ErrorHttpVersionNotSupported("err").into();
        assert_eq!(res.status(), StatusCode::HTTP_VERSION_NOT_SUPPORTED);

        let res: HttpResponse = ErrorVariantAlsoNegotiates("err").into();
        assert_eq!(res.status(), StatusCode::VARIANT_ALSO_NEGOTIATES);

        let res: HttpResponse = ErrorInsufficientStorage("err").into();
        assert_eq!(res.status(), StatusCode::INSUFFICIENT_STORAGE);

        let res: HttpResponse = ErrorLoopDetected("err").into();
        assert_eq!(res.status(), StatusCode::LOOP_DETECTED);

        let res: HttpResponse = ErrorNotExtended("err").into();
        assert_eq!(res.status(), StatusCode::NOT_EXTENDED);

        let res: HttpResponse = ErrorNetworkAuthenticationRequired("err").into();
        assert_eq!(res.status(), StatusCode::NETWORK_AUTHENTICATION_REQUIRED);
    }
}