https://github.com/michaelvanstraten/actix-error-mapper-middleware
Remap actix-web errors to your own custom error type
https://github.com/michaelvanstraten/actix-error-mapper-middleware
actix actix-web actix-web-middleware error-handling rust
Last synced: 2 months ago
JSON representation
Remap actix-web errors to your own custom error type
- Host: GitHub
- URL: https://github.com/michaelvanstraten/actix-error-mapper-middleware
- Owner: michaelvanstraten
- License: mit
- Created: 2022-06-01T10:43:24.000Z (about 3 years ago)
- Default Branch: master
- Last Pushed: 2022-09-07T06:14:14.000Z (almost 3 years ago)
- Last Synced: 2025-04-01T16:59:49.291Z (2 months ago)
- Topics: actix, actix-web, actix-web-middleware, error-handling, rust
- Language: Rust
- Homepage: https://docs.rs/actix-error-mapper-middleware/
- Size: 4.88 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
- License: LICENSE
Awesome Lists containing this project
README
# Actix-error-mapper-middleware
This simple crate allows you to remap actix-web errors to your own custom error type. You could for example return a html wrapped error.
## Example
Your custom error trait has to implement the
```std::convert::From``` and the ```actix_web::ResponseError``` traits.```rust
use actix_error_mapper_middleware::MapperService;
use actix_jwt_auth_middleware::{AuthService, Authority};
use actix_web::{web, App, Error as ActixError, HttpResponse, HttpServer, ResponseError};
use rusty_html::{html, HTMLify};#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(move || {
App::new()
// this wrap will catch every error thrown in the Apps scope an convert it to the MyError type
.wrap(MapperService::::new())
.service(
web::scope("")
// this service will throw an error if you are not logged in
.wrap(AuthService::new(Authority::::default())),
)
})
.bind("127.0.0.1:8080")?
.run()
.await
}#[derive(Debug)]
struct MyError {
error: ActixError,
}impl std::convert::From for MyError {
fn from(error: ActixError) -> Self {
Self { error }
}
}impl std::fmt::Display for MyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"An error occurred: \"{}\"",
self.error.to_string()
))
}
}impl ResponseError for MyError {
fn status_code(&self) -> actix_web::http::StatusCode {
self.error.as_response_error().status_code()
}fn error_response(&self) -> actix_web::HttpResponse {
HttpResponse::build(self.status_code()).body(html!(
Error
Ups . . .
{self.to_string()}
))
}
}
```