axum-service-errors
A Rust crate that provides structured error responses for Axum web applications.
Features
- Structured Error Handling: Define errors with error codes, names, HTTP status codes, and messages
- Zero-Copy Strings: Uses
Cow<'a, str>for efficient string handling - Message Formatting: Support for parameterized messages with argument binding
- Pluggable Response Builders: Customize response formats (plain text, JSON, or custom)
- Axum Integration: Implements
IntoResponsefor seamless use in Axum handlers - Serialization Support: Serde support for error serialization
- Optional JSON Feature: Enable JSON responses with the
jsonfeature flag
Installation
Add this to your Cargo.toml:
[]
= "0.1.0"
# Enable JSON support (optional)
= { = "0.1.0", = ["json"] }
Quick Start
use ServiceError;
use ;
async
async
Usage Examples
Basic Error Creation
use ServiceError;
// Create a basic error
let error = new;
Message Formatting with Arguments
// Error with parameterized message
let error = new
.bind
.bind;
// Results in: "Invalid email address for field user.email"
Adding Parameters
// Add optional parameters for additional context
let error = new
.parameter
.parameter;
JSON Response Builder (with json feature)
use ;
let error = new
.parameter
.with_response_builder;
// Returns JSON response:
// {
// "code": 1001,
// "name": "VALIDATION_ERROR",
// "message": "Invalid input",
// "parameters": {
// "field": "email"
// }
// }
Custom Response Builder
use ;
;
let error = new
.with_response_builder;
Features
Default Features
- Plain text response formatting
- Basic error structure with code, name, status, and message
- Message formatting with arguments
- Optional parameters support
JSON Feature
Enable with features = ["json"] in your Cargo.toml:
[]
= { = "0.1.0", = ["json"] }
Provides:
JsonResponseBuilderfor JSON-formatted error responses- Automatic JSON serialization of error data
Error Structure
The ServiceError struct contains:
code: Internal error code (u32)name: Error type name (e.g., "VALIDATION_ERROR")http_status: HTTP status code for the responsemessage: Human-readable error messagearguments: Values for message formatting (not serialized)parameters: Optional key-value pairs for additional contextresponse_builder: Optional custom response formatter (not serialized)
Development
Building
Running Tests
# Run all tests
# Run tests with JSON feature
Formatting and Linting
License
This project is licensed under the MIT License.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.