FAQ - Help and questions

How do I return custom errors from actix-web handlers with ResponseError?

#actix-web#error-handling#json#webpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Define an error enum that implements Display and actix-web ResponseError, choosing the status code and the JSON body in it. Handlers then return Result<T, AppError> and use the question mark. Log internal detail on the server and send the client only a generic message.

Checked with rustc 1.93.0, actix-web 4.21.0, tokio 1.54.1, Windows 11; driven with actix_web::test

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

ResponseError is the trait that turns an error into an HTTP response. Implement status_code and, for a custom body, error_response:

src/main.rsrust
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));
    }
}
text
/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 u32
  • NotFound gave 404 with a JSON body; Internal gave 500 with the generic text internal 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. The Display text is what self.to_string() returns, and it ends up in the response here, so keep it generic.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet