#actix-web #traits #error-response #status-code #macro #enums

macro awred

A convenient derive macro for actix_web::ResponseError trait

3 unstable releases

0.2.0 Sep 26, 2021
0.1.1 Sep 25, 2021
0.1.0 Sep 25, 2021

#23 in #status-code

25 downloads per month

MIT license

10KB
126 lines

awred

A convenient derive macro for actix_web::ResponseError trait.

Example

With Enum

use awred::ResponseError;
use serde::Serialize;
use thiserror::Error;

#[derive(Debug, Error, ResponseError, Serialize)]
pub enum AnError {
    #[error("Requested resource was not found")]
    #[status_code(NOT_FOUND)]
    ResourceNotFound,

    #[error("Forbidden: {reason}")]
    #[status_code(FORBIDDEN)]
    Forbidden { reason: String },

    // Internal Server Error
    #[error(transparent)]
    #[serde(skip)]
    IoError(#[from] std::io::Error),
}

With Struct

#[derive(Debug, Error, ResponseError, Serialize)]
#[error("Invalid username or password")]
#[status_code(BAD_REQUEST)]
pub struct InvalidCredentials;

Details

  • Status codes (from actix_web::http::StatusCode) are specified with #[status_code(...)] attribute
  • Variants/structs without #[status_code(...)] attribute return Internal Server Error with empty body
  • Response body consists of serialised error and message (error.to_string())

Error response body format

{
    "error": "error",
    "message": "error.to_string()",
}

Dependencies

~1.5MB
~34K SLoC