axum_error_object/
response.rs

1use axum::http::StatusCode;
2use axum::response::{IntoResponse, Response};
3
4#[derive(Debug)]
5#[must_use]
6pub struct ErrorResponse {
7    response: Response,
8    source: Option<anyhow::Error>,
9}
10
11impl ErrorResponse {
12    pub(crate) fn from_response(response: Response) -> Self {
13        Self { response, source: None }
14    }
15
16    /// Returns the wrapped error contained by this error response.
17    pub fn error(&self) -> Option<&anyhow::Error> {
18        self.source.as_ref()
19    }
20}
21
22impl<E> From<E> for ErrorResponse
23where
24    E: Into<anyhow::Error>,
25{
26    fn from(error: E) -> Self {
27        // unhandled fallback converts errors into an opaque 500 response
28        let error = error.into();
29        let response = StatusCode::INTERNAL_SERVER_ERROR.into_response();
30
31        Self { response, source: Some(error) }
32    }
33}
34
35impl IntoResponse for ErrorResponse {
36    fn into_response(self) -> Response {
37        self.response
38    }
39}