proof_route

Attribute Macro proof_route 

Source
#[proof_route]
Expand description

This macro attribute wraps actix http route handlers, due to the limitation where the attribute definition order is undefined this macro also wraps the actix_web::{get, post, put, patch, delete, options, trace} macros.

The usage in a route handler is the following.

use actix_error_proc::{ActixError, Error, HttpResult}; // Error is a thiserror re export.
use crate::models::user::User;
use actix_web::{main, App, HttpServer}
use serde_json::{from_slice, Error as JsonError};
use std::io::Error as IoError;

// assuming we have a wrapped enum
#[derive(ActixError, Error, Debug)]
enum SomeError {
    #[error("The body could not be parsed.")]
    #[status_code(BadRequest)]
    InvalidBody(#[from] JsonError)
}

#[proof_route(post("/users"))]
async fn some_route(body: Bytes) -> HttpResult<SomeError> {
    let user: User = from_slice(body)?; // notice the use of `?`.

    // Do something with the user.

    Ok(HttpResponse::NoContent()) // return Ok if everything went fine.
}

async fn main() -> IoError {
    HttpServer::new(|| {
        App::new()
            .service(some_route) // we can register the route normally.
    })
        .bind(("0.0.0.0", 8080))?
        .run()
        .await
}

There is an extra attribute we can add to route collectors to override it’s error status code, in the case we don’t want the original status code or we didn’t create the collector and the original error does not match our expectations we can use #[or], which lets us specify an error branch from any type instance that implements Into<HttpResponse>.

#[proof_route(post("/"))]
async fn route(#[or(SomeError::InvalidUser)] user: Json<User>) // ...

In this case if Json<User> fails while collecting from the http request whatever <SomeError::InvalidUser as Into<actix_web::HttpResponse>>.into() returns will be passed directly as a response for the route.

If you don’t add the attribute, the request will be collected as normal and in the case of any error the original error implementation for that collector will be applied.