1
0
mirror of https://github.com/actix/actix-website synced 2024-11-27 18:12:57 +01:00

Improve error handler example (#248)

This commit is contained in:
Mark Lodato 2021-12-22 13:36:35 -05:00 committed by GitHub
parent b0cf4ffae6
commit 3167a55853
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2,9 +2,9 @@
// <error-handler>
use actix_web::middleware::errhandlers::{ErrorHandlerResponse, ErrorHandlers};
use actix_web::{dev, http, HttpResponse, Result};
use actix_web::{dev, http, web, App, HttpResponse, HttpServer, Result};
fn render_500<B>(mut res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
fn add_error_header<B>(mut res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
res.response_mut().headers_mut().insert(
http::header::CONTENT_TYPE,
http::HeaderValue::from_static("Error"),
@ -14,18 +14,15 @@ fn render_500<B>(mut res: dev::ServiceResponse<B>) -> Result<ErrorHandlerRespons
#[actix_web::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer};
HttpServer::new(|| {
App::new()
.wrap(
ErrorHandlers::new()
.handler(http::StatusCode::INTERNAL_SERVER_ERROR, render_500),
)
.wrap(ErrorHandlers::new().handler(
http::StatusCode::INTERNAL_SERVER_ERROR,
add_error_header,
))
.service(
web::resource("/test")
.route(web::get().to(|| HttpResponse::Ok()))
.route(web::head().to(|| HttpResponse::MethodNotAllowed())),
web::resource("/")
.route(web::get().to(HttpResponse::InternalServerError)),
)
})
.bind("127.0.0.1:8080")?