From 5710b0d3299f183b54dc10d30e6d0fb7b44a2815 Mon Sep 17 00:00:00 2001 From: Stig Johan Berggren Date: Sun, 15 Mar 2020 12:19:11 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=9D=20Improve=20the=20code=20example?= =?UTF-8?q?=20for=20JsonConfig?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/types/json.rs | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/types/json.rs b/src/types/json.rs index fb00bf7a6..a87b368fb 100644 --- a/src/types/json.rs +++ b/src/types/json.rs @@ -208,8 +208,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)] @@ -222,6 +224,21 @@ where /// format!("Welcome {}!", info.username) /// } /// +/// /// Create custom error response +/// +/// /// 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") @@ -232,10 +249,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)) /// );