Answer#
ResponseError is the trait that turns an error into an HTTP response. Implement status_code and, for a custom body, error_response:
use actix_web::{get, http::StatusCode, test, web, App, HttpResponse, ResponseError};
use std::fmt;
#[derive(Debug)]
enum AppError { NotFound, Internal(String) }
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AppError::NotFound => write!(f, "not found"),
AppError::Internal(_) => write!(f, "internal error"), // what the client sees: no detail
}
}
}
impl ResponseError for AppError {
fn status_code(&self) -> StatusCode {
match self {
AppError::NotFound => StatusCode::NOT_FOUND,
AppError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
}
}
fn error_response(&self) -> HttpResponse {
if let AppError::Internal(detail) = self { eprintln!("log only: {detail}"); }
HttpResponse::build(self.status_code()).json(serde_json::json!({ "error": self.to_string() }))
}
}
#[get("/items/{id}")]
async fn item(id: web::Path<u32>) -> Result<String, AppError> {
match *id {
1 => Ok("item 1".into()),
0 => Err(AppError::Internal("connection refused: 10.0.0.5:5432".into())),
_ => Err(AppError::NotFound),
}
}
#[actix_web::main]
async fn main() {
let app = test::init_service(App::new().service(item)).await;
for uri in ["/items/1", "/items/9", "/items/0", "/items/abc"] {
let res = test::call_service(&app, test::TestRequest::get().uri(uri).to_request()).await;
let status = res.status();
println!("{uri} -> {status} {}", String::from_utf8_lossy(&test::read_body(res).await));
}
}/items/1 -> 200 OK item 1
/items/9 -> 404 Not Found {"error":"not found"}
log only: connection refused: 10.0.0.5:5432
/items/0 -> 500 Internal Server Error {"error":"internal error"}
/items/abc -> 404 Not Found can not parse "abc" to a u32NotFoundgave 404 with a JSON body;Internalgave 500 with the generic textinternal error. The database detail (10.0.0.5:5432) went to the log line, not to the client.- The last request,
/items/abc, never reached the handler:web::Path<u32>failed to parse and actix-web answered 404 with its own text (can not parse "abc" to a u32).
Common mistakes#
- Putting
error.to_string()of internal errors into the response. - Writing the full internal detail into
Display. TheDisplaytext is whatself.to_string()returns, and it ends up in the response here, so keep it generic.
Related questions#
Is this the same as axum's IntoResponse?#
The idea is the same: one error type decides status and body. In axum the trait is IntoResponse (see the thread on an axum error type).
Sources#
- actix-web,
ResponseError: https://docs.rs/actix-web/4.21.0/actix_web/error/trait.ResponseError.html (read 2026-12-05)