#error-derive #error #actix-web #derive #http

macro actix-web-error-derive

Derive macros for actix-web-error

2 unstable releases

0.2.0 May 5, 2023
0.1.0 Aug 15, 2022

#15 in #error-derive

Download history 12/week @ 2024-01-15 57/week @ 2024-01-22 1/week @ 2024-01-29 3/week @ 2024-02-05 40/week @ 2024-02-19 40/week @ 2024-02-26 16/week @ 2024-03-04 22/week @ 2024-03-11 6/week @ 2024-03-18 9/week @ 2024-03-25 42/week @ 2024-04-01 18/week @ 2024-04-08 22/week @ 2024-04-15 10/week @ 2024-04-22

93 downloads per month
Used in actix-web-error

MIT/Apache

21KB
489 lines

actix-web-error

Error responses for actix-web made easy. This crate will make it easy implementing actix_web::ResponseError for errors by providing a thiserror-like API for specifying an HTTP status. It's best used in combination with thiserror.

Currently, only a JSON response is supported.

Thanks to the aforementioned thiserror project, I used the core structure and core utilities.

Error Responses

  • Json will respond with JSON in the form of { "error": <Display representation> } (application/json).
  • Text will respond with the Display representation of the error (text/plain).

Example

#[derive(Debug, thiserror::Error, actix_web_error::Json)]
#[status(BAD_REQUEST)] // default status for all variants
enum MyError {
    #[error("Missing: {0}")]
    MissingField(&'static str),
    #[error("Malformed Date")]
    MalformedDate,
    #[error("Internal Server Error")]
    #[status(500)] // specific override
    Internal,
}

#[derive(Debug, thiserror::Error, actix_web_error::Text)]
#[error("Item not found")]
#[status(404)]
struct MyOtherError;

This will roughly expand to:

use actix_web::{ResponseError, HttpResponse, HttpResponseBuilder, http::StatusCode};

#[derive(Debug, thiserror::Error)]
enum MyError {
    #[error("Missing: {0}")]
    MissingField(&'static str),
    #[error("Malformed Date")]
    MalformedDate,
    #[error("Internal Server Error")]
    Internal,
}

#[derive(Debug, thiserror::Error)]
#[error("Item not found")]
struct MyOtherError;

impl ResponseError for MyError {
    fn status_code(&self) -> StatusCode {
        match self {
            Self::Internal => StatusCode::from_u16(500).unwrap(),
            _ => StatusCode::BAD_REQUEST,
        }
    }

    fn error_response(&self) -> HttpResponse {
        HttpResponseBuilder::new(self.status_code())
            .json(serde_json::json!({ "error": self.to_string() }))
    }
}

impl ResponseError for MyOtherError {
    fn status_code(&self) -> StatusCode {
        // With at least opt-level=1, this unwrap will be removed,
        // so this function will essentially return a constant.
        StatusCode::from_u16(404).unwrap()
    }
}

Dependencies

~0.8–1.3MB
~28K SLoC