{"id":1201,"hash":"a2f14841361b8281bd5eadd1ec5c32893e05384e2300b7f1ff885845bca16265","pattern":"How to return both success and error case in the same Axum handler?","full_message":"Ok so I have an axum handler which looks somewhat like this:\n\n#[debug_handler]\nasync fn handler(\n    State(server_state): State<Arc<Server>>,\n    Query(query_params): Query<Query>,\n) -> impl IntoResponse {\n    match server_state.store.handle(query_params).await {\n        Ok(res) => (StatusCode::OK, Json(res)),\n        Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, Json(err))\n    }\n}\n\nThis fails with the following error:\n\n   |\n42 | /     match server_state.store.handle(query_params).await {\n43 | |         Ok(res) => (StatusCode::OK, Json(res)),\n   | |                   -------------------------- this is found to be of type `(StatusCode, axum::Json<Vec<Data>>)`\n44 | |         Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, Json(err))\n   | |                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `Vec`, found enum `sqlx::Error`\n45 | |     }\n   | |_____- `match` arms have incompatible types\n   |\n   = note: expected tuple `(StatusCode, axum::Json<Vec<Data>>)`\n              found tuple `(StatusCode, axum::Json<sqlx::Error>)`\n\nI understand why the error is happening. The two arms of the match expression don't have the same return type.\n\nBut 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.\n\nThe other approach I can think of is to have a response struct...something like\n\nstruct Response {\n   body: Option<Data>,\n   error: Option<sqlx::Error>\n}\n\nand error will be None in case of success. body will be None in case of error.\n\nThe question is, I am not sure if this is the generally acceptable way of handling this with Axum?","ecosystem":"cargo","package_name":"rust-axum","package_version":null,"solution":"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:\n\n match server_state.store.handle(query_params).await {\n    Ok(res) => (StatusCode::OK, Json(res)).into_response(),\n    Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, Json(err)).into_response()\n}\n\nBest regards Thomas","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/74968993/how-to-return-both-success-and-error-case-in-the-same-axum-handler","votes":7,"created_at":"2026-04-19T04:52:35.593172+00:00","updated_at":"2026-04-19T04:52:35.593172+00:00"}