Actix-web error handle

How should I handle error responses uniformly in an actix-web server.
finding way to process all error message into json response in something like middleware.

actix-web = "4.3.1"

I use an error enum/struct and implement ResponseError + Serialize for that. No need for a middleware, as you can create your json inside ResponseError:

impl actix_web::error::ResponseError for Error {
    fn error_response(&self) -> HttpResponse {
         let mut res = HttpResponseBuilder::new(self.status_code());
         res.json(self)
    }
}

Then I return Result<impl Responder, Error> from my endpoints and that's it. I send nice error messages as json to my clients.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.