{"id":1194,"hash":"903eaadeee5124d117b12bd0406af63dd765c3794a559bec8a68fbe2761feabc","pattern":"actix_web middleware ErrorHandlers return error message in ServiceResponse","full_message":"I am trying to capture errors that may occur for requests made to my server. \n\nThis came up when I was receiving a 400 on one of my POST requests (which was thrown before even getting to my request handler method) and I was receiving no feedback as to what the issue was after enabling the debug logs I saw the issue \n\n[actix_web::types::json] Failed to deserialize Json from payload. Request path: /new_endpoint\nJson deserialize error: invalid length: expected one of [36, 32], found 10 at line 2 column 20\n[DEBUG actix_web::middleware::logger] Error in response: Deserialize(Error(\"invalid length: expected one of [36, 32], found 10\", line: 2, column: 20))\n\nNow, I want to be able to capture that error so that it can be sent back in the body of the 400 response. \n\nI've started with \n\nApp::new()\n    .wrap(ErrorHandlers::new().handler(http::StatusCode::BAD_REQUEST, handle_bad_request))\n\nand in handle_bad_request I am able to modify the response body to contain new information\n\nfn handle_bad_request<B>(mut res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<Body>> {\n    res.response_mut().headers_mut().insert(\n        http::header::CONTENT_TYPE,\n        http::HeaderValue::from_static(\"application/json\"),\n    );\n    let new_res: ServiceResponse<Body> = res.map_body(|_head, _body| {\n        ResponseBody::Other(Body::Message(Box::new(\"New Response Body\")))\n    });\n    Ok(ErrorHandlerResponse::Response(new_res))\n}\n\nIdeally what I want to do is take the error in ServiceResponse and send it back in the response. I am able to read the error by doing\n\nmatch res.response().error() {\n    Some(e) =>  println!(\"{0}\", e),\n    None =>  println!(\"Error None\")\n};\n\nbut as for actually taking that error and sending it back in the response I am not able to figure that out.","ecosystem":"cargo","package_name":"actix-web","package_version":null,"solution":"To solve this format!(\"{:?}\", res.reponse().error()) was needed. That does return Some(error message) so just to account for that the following worked.\n\nlet errorMsg: String = match res.response().error() {\n    Some(e) => format!(\"{:?}\", e),\n    None =>  String::from(\"Unknown Error\")\n};\nlet new_res: ServiceResponse<Body> = res.map_body(|_head, _body| {\n    ResponseBody::Other(Body::Message(Box::new(errorMsg)))\n});\nOk(ErrorHandlerResponse::Response(new_res))","confidence":0.7000000000000001,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/60405947/actix-web-middleware-errorhandlers-return-error-message-in-serviceresponse","votes":6,"created_at":"2026-04-19T04:52:34.055248+00:00","updated_at":"2026-04-19T04:52:34.055248+00:00"}