From 0d958fabd7cb8051d59fdb1c3b5b781476000fa6 Mon Sep 17 00:00:00 2001 From: Stig Johan Berggren Date: Tue, 17 Mar 2020 00:23:54 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=9D=20Improve=20the=20code=20example?= =?UTF-8?q?=20for=20JsonConfig=20(#1418)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 📝 Improve the code example for JsonConfig * Remove a redundant comment --- src/types/json.rs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/types/json.rs b/src/types/json.rs index ead2d0c9a..df8aa4fc6 100644 --- a/src/types/json.rs +++ b/src/types/json.rs @@ -207,8 +207,10 @@ where /// Json extractor configuration /// +/// # Examples +/// /// ```rust -/// use actix_web::{error, web, App, FromRequest, HttpResponse}; +/// use actix_web::{error, web, App, FromRequest, HttpRequest, HttpResponse}; /// use serde_derive::Deserialize; /// /// #[derive(Deserialize)] @@ -221,6 +223,19 @@ where /// format!("Welcome {}!", info.username) /// } /// +/// /// Return either a 400 or 415, and include the error message from serde +/// /// in the response body +/// fn json_error_handler(err: error::JsonPayloadError, _req: &HttpRequest) -> error::Error { +/// let detail = err.to_string(); +/// let response = match &err { +/// error::JsonPayloadError::ContentType => { +/// HttpResponse::UnsupportedMediaType().content_type("text/plain").body(detail) +/// } +/// _ => HttpResponse::BadRequest().content_type("text/plain").body(detail), +/// }; +/// error::InternalError::from_response(err, response).into() +/// } +/// /// fn main() { /// let app = App::new().service( /// web::resource("/index.html") @@ -231,10 +246,7 @@ where /// .content_type(|mime| { // <- accept text/plain content type /// mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN /// }) -/// .error_handler(|err, req| { // <- create custom error response -/// error::InternalError::from_response( -/// err, HttpResponse::Conflict().finish()).into() -/// }) +/// .error_handler(json_error_handler) // Use our custom error response /// })) /// .route(web::post().to(index)) /// );