actix_web/error/
error.rs

1use std::{error::Error as StdError, 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}
18
19impl Error {
20    /// Returns the reference to the underlying `ResponseError`.
21    pub fn as_response_error(&self) -> &dyn ResponseError {
22        self.cause.as_ref()
23    }
24
25    /// Similar to `as_response_error` but downcasts.
26    pub fn as_error<T: ResponseError + 'static>(&self) -> Option<&T> {
27        <dyn ResponseError>::downcast_ref(self.cause.as_ref())
28    }
29
30    /// Shortcut for creating an `HttpResponse`.
31    pub fn error_response(&self) -> HttpResponse {
32        self.cause.error_response()
33    }
34}
35
36impl fmt::Display for Error {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        fmt::Display::fmt(&self.cause, f)
39    }
40}
41
42impl fmt::Debug for Error {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        write!(f, "{:?}", &self.cause)
45    }
46}
47
48impl StdError for Error {
49    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
50        None
51    }
52}
53
54/// `Error` for any error that implements `ResponseError`
55impl<T: ResponseError + 'static> From<T> for Error {
56    fn from(err: T) -> Error {
57        Error {
58            cause: Box::new(err),
59        }
60    }
61}
62
63impl From<Box<dyn ResponseError>> for Error {
64    fn from(value: Box<dyn ResponseError>) -> Self {
65        Error { cause: value }
66    }
67}
68
69impl From<Error> for Response<BoxBody> {
70    fn from(err: Error) -> Response<BoxBody> {
71        err.error_response().into()
72    }
73}