Finlay Weber
Finlay Weber

Reputation: 4163

How to return both success and error case in the same Axum handler?

Ok so I have an axum handler which looks somewhat like this:

#[debug_handler]
async fn handler(
    State(server_state): State<Arc<Server>>,
    Query(query_params): Query<Query>,
) -> impl IntoResponse {
    match server_state.store.handle(query_params).await {
        Ok(res) => (StatusCode::OK, Json(res)),
        Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, Json(err))
    }
}

This fails with the following error:

   |
42 | /     match server_state.store.handle(query_params).await {
43 | |         Ok(res) => (StatusCode::OK, Json(res)),
   | |                   -------------------------- this is found to be of type `(StatusCode, axum::Json<Vec<Data>>)`
44 | |         Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, Json(err))
   | |                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `Vec`, found enum `sqlx::Error`
45 | |     }
   | |_____- `match` arms have incompatible types
   |
   = note: expected tuple `(StatusCode, axum::Json<Vec<Data>>)`
              found tuple `(StatusCode, axum::Json<sqlx::Error>)`

I understand why the error is happening. The two arms of the match expression don't have the same return type.

But the question is how to fix this? I am not sure it makes sense to have to convert somehow sqlx::Error into the ok case.

The other approach I can think of is to have a response struct...something like

struct Response {
   body: Option<Data>,
   error: Option<sqlx::Error>
}

and error will be None in case of success. body will be None in case of error.

The question is, I am not sure if this is the generally acceptable way of handling this with Axum?

Upvotes: 7

Views: 4557

Answers (1)

mazi
mazi

Reputation: 121

a little bit a late answer, but i think the easiest way to do it in this case is to apply into_response() to both match-arm results:

 match server_state.store.handle(query_params).await {
    Ok(res) => (StatusCode::OK, Json(res)).into_response(),
    Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, Json(err)).into_response()
}

Best regards Thomas

Upvotes: 12

Related Questions