Crates.io | actix-error-derive |
lib.rs | actix-error-derive |
version | 0.2.6 |
source | src |
created_at | 2024-02-18 19:53:45.898193 |
updated_at | 2024-02-23 12:08:29.016995 |
description | A simple library to handle REST errors, with a derive macro to generate the error type. It also provides a compatibility layer with actix-web. |
homepage | |
repository | https://github.com/INSAgenda/resterror |
max_upload_size | |
id | 1144349 |
size | 12,183 |
The derive(AsApiError)
library provides a powerful, derive macro for Rust developers working with Actix-Web to easily convert enum variants into structured API errors. This library simplifies error handling in web applications by enabling automatic mapping of custom error types to HTTP response errors.
[dependencies]
actix_error = "0.2.5"
Use the #[derive(AsApiError)]
macro on enums to define your error types. Customize each variant with #[error] attributes to specify HTTP status codes, error messages, and more.
Implement your Actix-Web handlers to return your custom errors. The AsApiErrorTrait
ensures they are automatically converted into appropriate HTTP responses.
async fn my_handler() -> Result<HttpResponse, MyError> {
// Your handler logic here...
Err(MyError::NotFound)
}
For errors requiring additional context, use named or unnamed fields directly in your enum variants.
#[derive(AsApiError)]
pub enum DetailedError {
#[error(code = 500, msg = "Unexpected error occurred: {0}")]
SystemError(String),
#[error(status = "BadRequest", msg = "Invalid input: {field}")]
ValidationError { field: DataField },
}
#[derive(AsApiError)]
pub enum Error {
#[error(group)]
Detailed(DetailedError), // Group errors together
#[error(code = 500, msg = "Database error occurred", ignore)]
DatabaseError(PostgresError), // Ignore the unnamed field
}
{
"kind": "system_error",
"message": "Unexpected error occurred: Internal Server Error"
}