apiresponse
A Rust library for standardized API error handling with derive macro support.
Features
- Derive Macro: Implement
Responsetrait automatically via#[derive(Response)] - Explicit Error Codes: Every error variant requires an explicit code for API stability
- Transparent Error Delegation: Proper error propagation through
transparentvariants - HTTP Status Code Support: Attach HTTP status codes to error variants
- Axum Integration: Built-in support for Axum web framework
- Type-safe: Compile-time validation of error codes
Installation
Add to your Cargo.toml:
[]
= "0.2.1"
= "1.0" # For error definitions
For Axum integration:
[]
= { = "0.2.1", = ["axum"] }
Quick Start
1. Define Your Error Type
use Response;
use Error;
2. Use the Error
let error = UserNotFound;
// Error code (from #[response(code = ...)])
println!;
// Output: 1000
// Error message (from #[error(...)]) / Display
println!;
// Output: User not found
// 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": "User not found",
// "data": null
// }
Core Features
🔢 Explicit Error Codes
Every variant must specify an error code. No implicit numbering means API contracts stay stable:
🔄 Transparent Error Delegation
Delegates error_code(), message(), and http_status_code() to the wrapped inner error:
// When AppError::Auth(AuthError::UserNotFound) occurs:
let error = Auth;
error.error_code // → 1000 (from AuthError)
error.message // → "User not found" (from AuthError)
error.http_status_code // → 404 (from AuthError)
🌐 HTTP Status Codes
Optionally attach HTTP status codes to variants. Defaults to 200:
Common Usage Patterns
RESTful API Error Handling
// In API handler
async
Error Aggregation
Axum Integration
use ;
use ApiResponse;
async
let app = new.route;
API Reference
Response Trait
ApiResponse Struct
Methods:
ApiResponse::success(data)— Create success response with dataApiResponse::ok()— Create empty success responseApiResponse::from_error(error)— Create error response from aResponseimplementor
Attributes
Variant-level Attributes
// ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^
// Required Optional (default 200)
// Delegate to inner error (code and status not needed)
Design Philosophy
- Explicit over Implicit: Error codes must be explicitly assigned for API stability
- Minimal by Default: Only three trait methods —
error_code(),message(),http_status_code() - Type Safety: Compile-time validation ensures every variant has an error code
- Framework Agnostic: Core library has no web framework dependencies; Axum is optional
Requirements
- Rust 1.70 or later
thiserrorfor error definitions (recommended)serdeandserde_jsonfor serialization
License
MIT OR Apache-2.0