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