Skip to content

Commit 09c1ed8

Browse files
committed
wrap AppError in Arc in Response Extensions
1 parent 556b579 commit 09c1ed8

File tree

1 file changed

+5
-7
lines changed

1 file changed

+5
-7
lines changed

examples/error-handling/src/main.rs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -147,17 +147,15 @@ where
147147
}
148148

149149
// The kinds of errors we can hit in our application.
150-
#[derive(Debug, Clone)]
150+
#[derive(Debug)]
151151
enum AppError {
152152
// The request body contained invalid JSON
153-
JsonRejection(Arc<JsonRejection>),
153+
JsonRejection(JsonRejection),
154154
// Some error from a third party library we're using
155155
TimeError(time_library::Error),
156156
}
157157

158158
// Tell axum how `AppError` should be converted into a response.
159-
//
160-
// This is also a convenient place to log errors.
161159
impl IntoResponse for AppError {
162160
fn into_response(self) -> Response {
163161
// How we want errors responses to be serialized
@@ -187,7 +185,7 @@ impl IntoResponse for AppError {
187185
let mut response = (status, AppJson(ErrorResponse { message })).into_response();
188186
if let Some(err) = err {
189187
// Insert our error into the response, our logging middleware will use this.
190-
response.extensions_mut().insert(err);
188+
response.extensions_mut().insert(Arc::new(err));
191189
}
192190
response
193191
}
@@ -196,7 +194,7 @@ impl IntoResponse for AppError {
196194
impl From<JsonRejection> for AppError {
197195
fn from(rejection: JsonRejection) -> Self {
198196
// Arc enables cloning of a JsonRejection
199-
Self::JsonRejection(Arc::new(rejection))
197+
Self::JsonRejection(rejection)
200198
}
201199
}
202200

@@ -210,7 +208,7 @@ impl From<time_library::Error> for AppError {
210208
async fn log_app_errors(request: Request, next: Next) -> Response {
211209
let response = next.run(request).await;
212210
// If the response contains an AppError Extension, log it.
213-
if let Some(err) = response.extensions().get::<AppError>() {
211+
if let Some(err) = response.extensions().get::<Arc<AppError>>() {
214212
tracing::error!(?err, "an unexpected error occurred inside a handler");
215213
}
216214
response

0 commit comments

Comments
 (0)