axum_error_macro

Crates.ioaxum_error_macro
lib.rsaxum_error_macro
version0.1.7
sourcesrc
created_at2023-08-21 11:45:37.493697
updated_at2023-10-22 22:34:27.033493
descriptionSimple derive macro for your custom Error enum to generate quickly its status code and message
homepagehttps://github.com/Huterok228/axum_error_macro
repositoryhttps://github.com/Huterok228/axum_error_macro
max_upload_size
id949915
size28,525
Huterok Bebrov (Huterenok)

documentation

https://docs.rs/axum_error_macro

README

Installation:

[dependencies]
axum_error_macro = { version = "0.1.7" }

Simple example

use axum_error_macro::ErrorResponse;
use axum::response::Response;

#[derive(ErrorResponse)]
#[error_format("application/json")]
enum Error {
  #[error(code = 500, msg = "Internal Server Error!!!")]
  InternalServerError,

  #[error(code = 400, msg = "Bad Request!!!")]
  BadRequest,

  #[error(code = 404, msg = "User by {} id was not found")]
  UserByIdNotFound(u32),

  #[error(code = 404, msg = "User by {} username with {} role was not found")]
  UserByUsernameAndRoleNotFound(String, String),

  #[error(code = 404, msg = "User {:?} was not found")]
  UserNotFound(User)
}

#[derive(Debug)]
struct User {
  username: String
}

fn server_error_handler() -> Response {
  return Error::InternalServerError.into_response();
}

fn user_by_id_handler() -> Response {
  return Error::UserByIdNotFound(1).into_response();
}

fn user_by_username_and_role_handler() -> Response {
  return Error::UserByUsernameAndRoleNotFound("Bebra".into(), "ADMIN".into()).into_response();
}

fn user_handler() -> Response {
  let user = User {
    username: "Bebra".into()
  };
  return Error::UserNotFound(user).into_response();
}

Also you can configure error response format with #[error_format(...)] macro. Today only "application/json" and "text/plain" are available.

Returned data will be in this format:

{
  "message": "Internal Server Error!!!"
}

or

Internal Server Error!!!
Commit count: 14

cargo fmt