| Crates.io | axum-error-handler |
| lib.rs | axum-error-handler |
| version | 0.2.1 |
| created_at | 2024-10-10 09:36:16.537778+00 |
| updated_at | 2025-07-05 06:24:05.487839+00 |
| description | A simple error handler for axum |
| homepage | |
| repository | https://github.com/MRDavidYen/axum-error-handler |
| max_upload_size | |
| id | 1403630 |
| size | 40,182 |
A procedural macro for generating standardized error responses in Axum applications. This crate provides a derive macro that automatically implements the IntoResponse trait for your error enums, creating consistent JSON error responses with proper HTTP status codes.
Note: This is an experimental project. The API may change in future versions.
Add this to your Cargo.toml:
[dependencies]
axum-error-handler = "0.2.1"
axum = "0.8"
thiserror = "2.0"
serde_json = "1.0"
use axum_error_handler::AxumErrorResponse;
use thiserror::Error;
#[derive(Debug, Error, AxumErrorResponse)]
pub enum AppError {
#[error("Bad request: {0}")]
#[status_code("400")]
#[code("BAD_REQUEST")]
BadRequest(String),
#[error("Internal server error {0}")]
#[status_code("500")]
#[code("INTERNAL_SERVER_ERROR")]
InternalError(String),
}
Generates JSON responses like:
{
"result": null,
"error": {
"code": "BAD_REQUEST",
"message": "Bad request: invalid input"
}
}
Use #[response(nested)] to delegate to inner error responses:
#[derive(Debug, Error, AxumErrorResponse)]
pub enum AppError {
#[error("Bad request: {0}")]
#[status_code("400")]
#[code("BAD_REQUEST")]
BadRequest(String),
#[error("{0}")]
#[response(nested)]
ServiceError(#[from] ServiceError),
}
#[derive(Debug, Error, AxumErrorResponse)]
pub enum ServiceError {
#[error("Authentication error: {0}")]
#[status_code("401")]
#[code("AUTHENTICATION_ERROR")]
AuthenticationError(String),
}
For specialized error handling, use custom response functions:
use axum_error_handler::{AxumErrorResponse, ErrorResponseContext};
use axum::{response::Response, http::StatusCode};
// Custom response function
fn custom_error_response(_ctx: ErrorResponseContext) -> Response {
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(axum::body::Body::from("Custom error format"))
.unwrap()
}
#[derive(Debug, Error, AxumErrorResponse)]
#[response(custom_fn = "custom_error_response")]
pub enum CustomError {
#[error("Database error: {0}")]
DatabaseError(String),
#[error("Validation error: {0}")]
ValidationError(String),
}
This allows you to return any response format (plain text, XML, custom JSON, etc.) instead of the standard JSON format.
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
This project is licensed under the MIT License - see the LICENSE file for details.
Find this project on GitHub: axum-error-handler