api-response
A Rust library for standardized API error handling with automatic module-based error code management and message formatting.
Features
- Automatic Module Prefixing: Error messages automatically include module paths in
[module] messageformat - Auto Error Code Numbering: Sequential error code allocation based on module and base code
- Transparent Error Delegation: Proper error propagation through
transparentvariants - HTTP Status Code Support: Attach HTTP status codes to error variants
- Web Framework Integration: Built-in support for Axum, Actix-web, and Poem
- Type-safe: Compile-time error code and module validation
- Zero Runtime Cost: All formatting logic uses efficient trait methods
Installation
Add to your Cargo.toml:
[]
= "0.1"
= "1.0" # For error definitions
For web framework integration:
[]
= { = "0.1", = ["axum"] } # or "actix", "poem"
Quick Start
1. Define Your Error Type
use Response;
use Error;
2. Use the Error
let error = UserNotFound;
// Automatic module prefix
println!;
// Output: [auth] User not found
// Error code (auto-numbered)
println!;
// Output: 1000
// HTTP status code
println!;
// Output: 404
3. Convert to API Response
use ApiResponse;
// Method 1: From error
let response = from_error;
// Method 2: From Result
let result: = Err;
let response: ApiResponse = result.into;
// Serialize to JSON
let json = to_string.unwrap;
// {
// "code": 1000,
// "message": "[auth] User not found",
// "data": null
// }
Core Features
🎯 Automatic Module Prefixing
Error messages automatically include module paths:
let err = InsufficientBalance;
err.message // → "[payment.stripe] Insufficient balance"
err.module_path // → "payment.stripe"
err.raw_message // → "Insufficient balance"
🔄 Transparent Error Delegation
Proper error propagation when wrapping errors:
// When ApiError::Auth(AuthError::UserNotFound) occurs:
let error = Auth;
error.message // → "[auth] User not found" (from AuthError)
error.module_path // → "auth" (from AuthError)
error.error_code // → 1000 (from AuthError)
🔢 Error Code Management
Automatic Numbering with base
Manual Code Assignment (No base)
Override Auto-numbering
No Module Attribute (Optional)
// Usage
let err = GenericError;
err.message // → "Generic error" (no module prefix)
err.module_path // → ""
Common Usage Patterns
RESTful API Error Handling
// In API handler
async
Error Aggregation
Web Framework Integration
Axum
use ;
use ApiResponse;
async
let app = new.route;
Actix-web
use ;
use ApiResponse;
async
Poem
use ;
use ApiResponse;
async
let app = new.at;
Examples
We provide comprehensive examples:
# Complete feature demonstration
# Web framework integration
API Reference
Response Trait
ApiResponse Struct
Methods:
ApiResponse::success(data)- Create success response with dataApiResponse::success_with_message(data, message)- Success with custom messageApiResponse::ok()- Create empty success response
Attributes
Enum-level Attributes
// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^
// Optional (default "") Optional (if omitted, variants must specify code)
Variant-level Attributes
// ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^
// Optional (override) Optional (default 200) Optional (override Display)
// Delegate to inner error
Advanced Features
Access Metadata
// Get module path
let module = error.module_path; // "auth.login"
// Raw vs Formatted messages
error.raw_message // → "User not found"
error.message // → "[auth.login] User not found"
Multi-level Module Names
// Messages will be prefixed with [api.v1.auth]
Design Philosophy
- Simple by Default: Minimal boilerplate, maximum functionality
- Type Safety: Compile-time validation of error codes and modules
- Flexibility: Support both auto-numbering and manual code assignment
- Zero Cost: All abstractions compile away to efficient code
- Framework Agnostic: Core library has no web framework dependencies
Requirements
- Rust 1.70 or later
thiserrorfor error definitions (recommended)serdeandserde_jsonfor serialization
License
MIT OR Apache-2.0
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.