axum_error_object/
response.rs1use 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 pub(crate) fn from_status(status: StatusCode) -> Self {
17 Self { response: status.into_response(), source: None }
18 }
19
20 pub(crate) fn with_source(self, source: anyhow::Error) -> Self {
21 Self { response: self.response, source: Some(source) }
22 }
23
24 pub fn error(&self) -> Option<&anyhow::Error> {
26 self.source.as_ref()
27 }
28}
29
30impl<E> From<E> for ErrorResponse
31where
32 E: Into<anyhow::Error>,
33{
34 fn from(error: E) -> Self {
35 let error = error.into();
37 let response = StatusCode::INTERNAL_SERVER_ERROR.into_response();
38
39 Self { response, source: Some(error) }
40 }
41}
42
43impl IntoResponse for ErrorResponse {
44 fn into_response(self) -> Response {
45 if let Some(source) = self.source {
46 tracing::error!("response error: {source:?}");
47 }
48
49 self.response
50 }
51}