Skip to main content

ErrorResponse

Derive Macro ErrorResponse 

Source
#[derive(ErrorResponse)]
{
    // Attributes available to this derive:
    #[default_status_code]
    #[status_code]
    #[transform_response]
}
Expand description

§ErrorResponse Derive Macro

This macro is a helper to implement Into<actix_web::HttpResponse> and Into<actix_web::Error> for thiserror::error marked enumerables.

Have in mind that nothing really enforces that the enum you apply this on has also derived thiserror::error, but this macro’s generation will rely on you having implemented Display, and thiserror::error is a convenient way to implement Display.

§Macro attributes

With ErrorResponse you can modify how your your response will look when returning an error from an endpoint.

#[transform_response(function_reference)] You can add this attribute to your enum and pass a static function reference the function should receive an HttpResponseBuilder which is the partially built response and a String as second argument, which is the result of <Self as Display>::to_string() where Self is the enum you applied this function to. The function should return an HttpResponse which is what’s going to be used when an error is returned from an endpoint.

#[default_status_code(number_or_identifier)] You can add this attribute to your enum and pass or either a number representing the http error status code like 400 or 500, or an identifier such as BadRequest or InternalServerError. This will set the status code by default if you don’t use status_code in any enum variant.

#[status_code(number_or_identifier)] Like default_status_code you can pass a number or an HTTP status code identifier and it will be applied to the current enum variant.

By default all status codes will be InternalServerError and the enum’s Display will be applied to the response body.

§Example

use actix_failwrap::ErrorResponse;
use thiserror::Error;
use serde_json::json;
use chrono::Utc;
use actix_web::{HttpResponse, HttpResponseBuilder};

fn transformer(mut builder: HttpResponseBuilder, display: String) -> HttpResponse {
    builder
        .body(json! {
            {
                "error": display,
                "date": Utc::now()
                    .to_rfc3339()
                    .to_string()
            }
        }.to_string())
}

#[derive(ErrorResponse, Error, Debug)]
#[transform_response(transformer)]
#[default_status_code(InternalServerError)] // this is already by default
enum CustomError {
    #[error("This password is already in use by {email}, please chose another.")]
    #[status_code(BadRequest)]
    PasswordAlreadyInUse { email: String } // :)
}

// This can then be used with the `proof_route` macro.