actix_web/error/error.rs
1use std::fmt;
2
3use actix_http::{body::BoxBody, Response};
4
5use crate::{HttpResponse, ResponseError};
6
7/// General purpose Actix Web error.
8///
9/// An Actix Web error is used to carry errors from `std::error` through Actix in a convenient way.
10/// It can be created through converting errors with `into()`.
11///
12/// Whenever it is created from an external object a response error is created for it that can be
13/// used to create an HTTP response from it this means that if you have access to an actix `Error`
14/// you can always get a `ResponseError` reference from it.
15pub struct Error {
16 cause: Box<dyn ResponseError>,
17 response_mappers: Vec<Box<dyn Fn(HttpResponse) -> HttpResponse>>,
18}
19
20impl_more::forward_display!(Error => cause);
21impl_more::impl_leaf_error!(Error);
22
23impl Error {
24 /// Returns the reference to the underlying `ResponseError`.
25 pub fn as_response_error(&self) -> &dyn ResponseError {
26 self.cause.as_ref()
27 }
28
29 /// Similar to `as_response_error` but downcasts.
30 pub fn as_error<T: ResponseError + 'static>(&self) -> Option<&T> {
31 <dyn ResponseError>::downcast_ref(self.cause.as_ref())
32 }
33
34 /// Shortcut for creating an `HttpResponse`.
35 pub fn error_response(&self) -> HttpResponse {
36 let mut res = self.cause.error_response();
37
38 for mapper in &self.response_mappers {
39 res = (mapper)(res);
40 }
41
42 res
43 }
44
45 /// Adds a function that maps the HTTP response generated for this error.
46 ///
47 /// Mappers are called in the order they are added each time
48 /// [`error_response`](Self::error_response) is called. A mapper may receive a response already
49 /// modified by other mappers, so it should avoid relying on a particular position in the chain.
50 ///
51 /// Prefer narrowly mutating the provided response. Preserve fields the mapper does not own,
52 /// insert default headers only when absent, and merge list-valued headers without introducing
53 /// duplicates. Mappers should also be deterministic and safe to call more than once.
54 ///
55 /// # Good
56 ///
57 /// This mapper preserves the error response and adds a default only when it is absent:
58 ///
59 /// ```
60 /// use actix_web::{
61 /// error,
62 /// http::header::{self, HeaderValue},
63 /// };
64 ///
65 /// let mut err = error::ErrorBadRequest("bad request");
66 /// err.add_response_mapper(|mut res| {
67 /// if !res.headers().contains_key(header::CACHE_CONTROL) {
68 /// res.headers_mut()
69 /// .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
70 /// }
71 ///
72 /// res
73 /// });
74 ///
75 /// assert_eq!(
76 /// err.error_response().headers().get(header::CACHE_CONTROL),
77 /// Some(&HeaderValue::from_static("no-store")),
78 /// );
79 /// ```
80 ///
81 /// # Bad
82 ///
83 /// Replacing the response discards the original status, body, headers, extensions, and any
84 /// changes made by earlier mappers:
85 ///
86 /// ```
87 /// use actix_web::{error, HttpResponse};
88 ///
89 /// let mut err = error::ErrorBadRequest("bad request");
90 /// err.add_response_mapper(|_| HttpResponse::InternalServerError().finish());
91 /// ```
92 pub fn add_response_mapper<F>(&mut self, mapper: F)
93 where
94 F: Fn(HttpResponse) -> HttpResponse + 'static,
95 {
96 self.response_mappers.push(Box::new(mapper))
97 }
98}
99
100impl fmt::Debug for Error {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 write!(f, "{:?}", self.cause)
103 }
104}
105
106/// `Error` for any error that implements `ResponseError`
107impl<T: ResponseError + 'static> From<T> for Error {
108 fn from(err: T) -> Error {
109 Error {
110 cause: Box::new(err),
111 response_mappers: Vec::new(),
112 }
113 }
114}
115
116impl From<Box<dyn ResponseError>> for Error {
117 fn from(value: Box<dyn ResponseError>) -> Self {
118 Error {
119 cause: value,
120 response_mappers: Vec::new(),
121 }
122 }
123}
124
125impl From<Error> for Response<BoxBody> {
126 fn from(err: Error) -> Response<BoxBody> {
127 err.error_response().into()
128 }
129}