added body manipulation example for error handlers

This commit is contained in:
Naiker 2023-02-06 21:26:33 +00:00
parent 359d5d5c80
commit 7f36b295d7
1 changed files with 21 additions and 0 deletions

View File

@ -50,6 +50,8 @@ type DefaultHandler<B> = Option<Rc<ErrorHandler<B>>>;
/// will pass by unchanged by this middleware. /// will pass by unchanged by this middleware.
/// ///
/// # Examples /// # Examples
/// ## Handler Response
/// Header
/// ``` /// ```
/// use actix_web::http::{header, StatusCode}; /// use actix_web::http::{header, StatusCode};
/// use actix_web::middleware::{ErrorHandlerResponse, ErrorHandlers}; /// use actix_web::middleware::{ErrorHandlerResponse, ErrorHandlers};
@ -67,6 +69,25 @@ type DefaultHandler<B> = Option<Rc<ErrorHandler<B>>>;
/// .wrap(ErrorHandlers::new().handler(StatusCode::INTERNAL_SERVER_ERROR, add_error_header)) /// .wrap(ErrorHandlers::new().handler(StatusCode::INTERNAL_SERVER_ERROR, add_error_header))
/// .service(web::resource("/").route(web::get().to(HttpResponse::InternalServerError))); /// .service(web::resource("/").route(web::get().to(HttpResponse::InternalServerError)));
/// ``` /// ```
///
/// Body Content
/// ```
/// fn add_error_body<B>(res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
/// // Get the error message and status code
/// let error_message = "An error occurred";
/// // Destructures ServiceResponse into request and response components
/// let (req, res) = res.into_parts();
/// // Create a new response with the modified body
/// let res = res.set_body(error_message).map_into_boxed_body();
/// // Create a new ServiceResponse with the modified response
/// let res = ServiceResponse::new(req, res).map_into_right_body();
/// Ok(ErrorHandlerResponse::Response(res))
///}
///
/// let app = App::new()
/// .wrap(ErrorHandlers::new().handler(StatusCode::INTERNAL_SERVER_ERROR, add_error_body))
/// .service(web::resource("/").route(web::get().to(HttpResponse::InternalServerError)));
/// ```
/// ## Registering default handler /// ## Registering default handler
/// ``` /// ```
/// # use actix_web::http::{header, StatusCode}; /// # use actix_web::http::{header, StatusCode};