4次发布
0.1.7 | 2023年10月22日 |
---|---|
0.1.6 | 2023年10月22日 |
0.1.4 | 2023年8月21日 |
#539 in 过程宏
每月64次下载
13KB
180 行
安装
[dependencies]
axum_error_macro = { version = "0.1.7" }
简单示例
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();
}
您还可以使用 #[error_format(...)] 宏配置错误响应格式。今天只有 "application/json" 和 "text/plain" 可用。
返回的数据将采用以下格式
{
"message": "Internal Server Error!!!"
}
或
Internal Server Error!!!
依赖项
~6–8.5MB
~155K SLoC