Skip to main content

actix_web/error/
internal.rs

1use std::{cell::RefCell, fmt, io::Write as _};
2
3use actix_http::{
4    body::BoxBody,
5    header::{self, TryIntoHeaderValue as _},
6    StatusCode,
7};
8use bytes::{BufMut as _, BytesMut};
9
10use crate::{Error, HttpRequest, HttpResponse, Responder, ResponseError};
11
12/// Wraps errors to alter the generated response status code.
13///
14/// In following example, the `io::Error` is wrapped into `ErrorBadRequest` which will generate a
15/// response with the 400 Bad Request status code instead of the usual status code generated by
16/// an `io::Error`.
17///
18/// # Examples
19/// ```
20/// # use std::io;
21/// # use actix_web::{error, HttpRequest};
22/// async fn handler_error() -> Result<String, actix_web::Error> {
23///     let err = io::Error::new(io::ErrorKind::Other, "error");
24///     Err(error::ErrorBadRequest(err))
25/// }
26/// ```
27pub struct InternalError<T> {
28    cause: T,
29    status: InternalErrorType,
30}
31
32impl_more::forward_debug!(<T> in InternalError<T> => cause);
33impl_more::forward_display!(<T> in InternalError<T> => cause);
34
35enum InternalErrorType {
36    Status(StatusCode),
37    Response(RefCell<Option<HttpResponse>>),
38}
39
40impl<T> InternalError<T> {
41    /// Constructs an `InternalError` with given status code.
42    pub fn new(cause: T, status: StatusCode) -> Self {
43        InternalError {
44            cause,
45            status: InternalErrorType::Status(status),
46        }
47    }
48
49    /// Constructs an `InternalError` with pre-defined response.
50    pub fn from_response(cause: T, response: HttpResponse) -> Self {
51        InternalError {
52            cause,
53            status: InternalErrorType::Response(RefCell::new(Some(response))),
54        }
55    }
56}
57
58impl<T> ResponseError for InternalError<T>
59where
60    T: fmt::Debug + fmt::Display,
61{
62    fn status_code(&self) -> StatusCode {
63        match self.status {
64            InternalErrorType::Status(st) => st,
65            InternalErrorType::Response(ref resp) => {
66                if let Some(resp) = resp.borrow().as_ref() {
67                    resp.head().status
68                } else {
69                    StatusCode::INTERNAL_SERVER_ERROR
70                }
71            }
72        }
73    }
74
75    fn error_response(&self) -> HttpResponse {
76        match self.status {
77            InternalErrorType::Status(status) => {
78                let mut res = HttpResponse::new(status);
79                let mut buf = BytesMut::new().writer();
80                let _ = write!(buf, "{}", self);
81
82                let mime = mime::TEXT_PLAIN_UTF_8.try_into_value().unwrap();
83                res.headers_mut().insert(header::CONTENT_TYPE, mime);
84
85                res.set_body(BoxBody::new(buf.into_inner()))
86            }
87
88            InternalErrorType::Response(ref resp) => {
89                if let Some(resp) = resp.borrow_mut().take() {
90                    resp
91                } else {
92                    HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR)
93                }
94            }
95        }
96    }
97}
98
99impl<T> Responder for InternalError<T>
100where
101    T: fmt::Debug + fmt::Display + 'static,
102{
103    type Body = BoxBody;
104
105    fn respond_to(self, _: &HttpRequest) -> HttpResponse<Self::Body> {
106        HttpResponse::from_error(self)
107    }
108}
109
110macro_rules! error_helper {
111    ($name:ident, $status:ident) => {
112        #[doc = concat!("Helper function that wraps any error and generates a `", stringify!($status), "` response.")]
113        #[allow(non_snake_case)]
114        pub fn $name<T>(err: T) -> Error
115        where
116            T: fmt::Debug + fmt::Display + 'static,
117        {
118            InternalError::new(err, StatusCode::$status).into()
119        }
120    };
121}
122
123error_helper!(ErrorBadRequest, BAD_REQUEST);
124error_helper!(ErrorUnauthorized, UNAUTHORIZED);
125error_helper!(ErrorPaymentRequired, PAYMENT_REQUIRED);
126error_helper!(ErrorForbidden, FORBIDDEN);
127error_helper!(ErrorNotFound, NOT_FOUND);
128error_helper!(ErrorMethodNotAllowed, METHOD_NOT_ALLOWED);
129error_helper!(ErrorNotAcceptable, NOT_ACCEPTABLE);
130error_helper!(
131    ErrorProxyAuthenticationRequired,
132    PROXY_AUTHENTICATION_REQUIRED
133);
134error_helper!(ErrorRequestTimeout, REQUEST_TIMEOUT);
135error_helper!(ErrorConflict, CONFLICT);
136error_helper!(ErrorGone, GONE);
137error_helper!(ErrorLengthRequired, LENGTH_REQUIRED);
138error_helper!(ErrorPayloadTooLarge, PAYLOAD_TOO_LARGE);
139error_helper!(ErrorUriTooLong, URI_TOO_LONG);
140error_helper!(ErrorUnsupportedMediaType, UNSUPPORTED_MEDIA_TYPE);
141error_helper!(ErrorRangeNotSatisfiable, RANGE_NOT_SATISFIABLE);
142error_helper!(ErrorImATeapot, IM_A_TEAPOT);
143error_helper!(ErrorMisdirectedRequest, MISDIRECTED_REQUEST);
144error_helper!(ErrorUnprocessableEntity, UNPROCESSABLE_ENTITY);
145error_helper!(ErrorLocked, LOCKED);
146error_helper!(ErrorFailedDependency, FAILED_DEPENDENCY);
147error_helper!(ErrorUpgradeRequired, UPGRADE_REQUIRED);
148error_helper!(ErrorPreconditionFailed, PRECONDITION_FAILED);
149error_helper!(ErrorPreconditionRequired, PRECONDITION_REQUIRED);
150error_helper!(ErrorTooManyRequests, TOO_MANY_REQUESTS);
151error_helper!(
152    ErrorRequestHeaderFieldsTooLarge,
153    REQUEST_HEADER_FIELDS_TOO_LARGE
154);
155error_helper!(
156    ErrorUnavailableForLegalReasons,
157    UNAVAILABLE_FOR_LEGAL_REASONS
158);
159error_helper!(ErrorExpectationFailed, EXPECTATION_FAILED);
160error_helper!(ErrorInternalServerError, INTERNAL_SERVER_ERROR);
161error_helper!(ErrorNotImplemented, NOT_IMPLEMENTED);
162error_helper!(ErrorBadGateway, BAD_GATEWAY);
163error_helper!(ErrorServiceUnavailable, SERVICE_UNAVAILABLE);
164error_helper!(ErrorGatewayTimeout, GATEWAY_TIMEOUT);
165error_helper!(ErrorHttpVersionNotSupported, HTTP_VERSION_NOT_SUPPORTED);
166error_helper!(ErrorVariantAlsoNegotiates, VARIANT_ALSO_NEGOTIATES);
167error_helper!(ErrorInsufficientStorage, INSUFFICIENT_STORAGE);
168error_helper!(ErrorLoopDetected, LOOP_DETECTED);
169error_helper!(ErrorNotExtended, NOT_EXTENDED);
170error_helper!(
171    ErrorNetworkAuthenticationRequired,
172    NETWORK_AUTHENTICATION_REQUIRED
173);
174
175#[cfg(test)]
176mod tests {
177    use actix_http::error::ParseError;
178
179    use super::*;
180
181    #[test]
182    fn test_internal_error() {
183        let err = InternalError::from_response(ParseError::Method, HttpResponse::Ok().finish());
184        let resp: HttpResponse = err.error_response();
185        assert_eq!(resp.status(), StatusCode::OK);
186    }
187
188    #[test]
189    fn test_error_helpers() {
190        let res: HttpResponse = ErrorBadRequest("err").into();
191        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
192
193        let res: HttpResponse = ErrorUnauthorized("err").into();
194        assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
195
196        let res: HttpResponse = ErrorPaymentRequired("err").into();
197        assert_eq!(res.status(), StatusCode::PAYMENT_REQUIRED);
198
199        let res: HttpResponse = ErrorForbidden("err").into();
200        assert_eq!(res.status(), StatusCode::FORBIDDEN);
201
202        let res: HttpResponse = ErrorNotFound("err").into();
203        assert_eq!(res.status(), StatusCode::NOT_FOUND);
204
205        let res: HttpResponse = ErrorMethodNotAllowed("err").into();
206        assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);
207
208        let res: HttpResponse = ErrorNotAcceptable("err").into();
209        assert_eq!(res.status(), StatusCode::NOT_ACCEPTABLE);
210
211        let res: HttpResponse = ErrorProxyAuthenticationRequired("err").into();
212        assert_eq!(res.status(), StatusCode::PROXY_AUTHENTICATION_REQUIRED);
213
214        let res: HttpResponse = ErrorRequestTimeout("err").into();
215        assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
216
217        let res: HttpResponse = ErrorConflict("err").into();
218        assert_eq!(res.status(), StatusCode::CONFLICT);
219
220        let res: HttpResponse = ErrorGone("err").into();
221        assert_eq!(res.status(), StatusCode::GONE);
222
223        let res: HttpResponse = ErrorLengthRequired("err").into();
224        assert_eq!(res.status(), StatusCode::LENGTH_REQUIRED);
225
226        let res: HttpResponse = ErrorPreconditionFailed("err").into();
227        assert_eq!(res.status(), StatusCode::PRECONDITION_FAILED);
228
229        let res: HttpResponse = ErrorPayloadTooLarge("err").into();
230        assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);
231
232        let res: HttpResponse = ErrorUriTooLong("err").into();
233        assert_eq!(res.status(), StatusCode::URI_TOO_LONG);
234
235        let res: HttpResponse = ErrorUnsupportedMediaType("err").into();
236        assert_eq!(res.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
237
238        let res: HttpResponse = ErrorRangeNotSatisfiable("err").into();
239        assert_eq!(res.status(), StatusCode::RANGE_NOT_SATISFIABLE);
240
241        let res: HttpResponse = ErrorExpectationFailed("err").into();
242        assert_eq!(res.status(), StatusCode::EXPECTATION_FAILED);
243
244        let res: HttpResponse = ErrorImATeapot("err").into();
245        assert_eq!(res.status(), StatusCode::IM_A_TEAPOT);
246
247        let res: HttpResponse = ErrorMisdirectedRequest("err").into();
248        assert_eq!(res.status(), StatusCode::MISDIRECTED_REQUEST);
249
250        let res: HttpResponse = ErrorUnprocessableEntity("err").into();
251        assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);
252
253        let res: HttpResponse = ErrorLocked("err").into();
254        assert_eq!(res.status(), StatusCode::LOCKED);
255
256        let res: HttpResponse = ErrorFailedDependency("err").into();
257        assert_eq!(res.status(), StatusCode::FAILED_DEPENDENCY);
258
259        let res: HttpResponse = ErrorUpgradeRequired("err").into();
260        assert_eq!(res.status(), StatusCode::UPGRADE_REQUIRED);
261
262        let res: HttpResponse = ErrorPreconditionRequired("err").into();
263        assert_eq!(res.status(), StatusCode::PRECONDITION_REQUIRED);
264
265        let res: HttpResponse = ErrorTooManyRequests("err").into();
266        assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS);
267
268        let res: HttpResponse = ErrorRequestHeaderFieldsTooLarge("err").into();
269        assert_eq!(res.status(), StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE);
270
271        let res: HttpResponse = ErrorUnavailableForLegalReasons("err").into();
272        assert_eq!(res.status(), StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS);
273
274        let res: HttpResponse = ErrorInternalServerError("err").into();
275        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
276
277        let res: HttpResponse = ErrorNotImplemented("err").into();
278        assert_eq!(res.status(), StatusCode::NOT_IMPLEMENTED);
279
280        let res: HttpResponse = ErrorBadGateway("err").into();
281        assert_eq!(res.status(), StatusCode::BAD_GATEWAY);
282
283        let res: HttpResponse = ErrorServiceUnavailable("err").into();
284        assert_eq!(res.status(), StatusCode::SERVICE_UNAVAILABLE);
285
286        let res: HttpResponse = ErrorGatewayTimeout("err").into();
287        assert_eq!(res.status(), StatusCode::GATEWAY_TIMEOUT);
288
289        let res: HttpResponse = ErrorHttpVersionNotSupported("err").into();
290        assert_eq!(res.status(), StatusCode::HTTP_VERSION_NOT_SUPPORTED);
291
292        let res: HttpResponse = ErrorVariantAlsoNegotiates("err").into();
293        assert_eq!(res.status(), StatusCode::VARIANT_ALSO_NEGOTIATES);
294
295        let res: HttpResponse = ErrorInsufficientStorage("err").into();
296        assert_eq!(res.status(), StatusCode::INSUFFICIENT_STORAGE);
297
298        let res: HttpResponse = ErrorLoopDetected("err").into();
299        assert_eq!(res.status(), StatusCode::LOOP_DETECTED);
300
301        let res: HttpResponse = ErrorNotExtended("err").into();
302        assert_eq!(res.status(), StatusCode::NOT_EXTENDED);
303
304        let res: HttpResponse = ErrorNetworkAuthenticationRequired("err").into();
305        assert_eq!(res.status(), StatusCode::NETWORK_AUTHENTICATION_REQUIRED);
306    }
307}