📝 Improve the code example for JsonConfig

This commit is contained in:
Stig Johan Berggren 2020-03-15 12:19:11 +01:00
parent 5da9e277a2
commit 5710b0d329
No known key found for this signature in database
GPG Key ID: 2B80D833E53D674A
1 changed files with 19 additions and 5 deletions

View File

@ -208,8 +208,10 @@ where
/// Json extractor configuration /// Json extractor configuration
/// ///
/// # Examples
///
/// ```rust /// ```rust
/// use actix_web::{error, web, App, FromRequest, HttpResponse}; /// use actix_web::{error, web, App, FromRequest, HttpRequest, HttpResponse};
/// use serde_derive::Deserialize; /// use serde_derive::Deserialize;
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
@ -222,6 +224,21 @@ where
/// format!("Welcome {}!", info.username) /// 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() { /// fn main() {
/// let app = App::new().service( /// let app = App::new().service(
/// web::resource("/index.html") /// web::resource("/index.html")
@ -232,10 +249,7 @@ where
/// .content_type(|mime| { // <- accept text/plain content type /// .content_type(|mime| { // <- accept text/plain content type
/// mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN /// mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
/// }) /// })
/// .error_handler(|err, req| { // <- create custom error response /// .error_handler(json_error_handler) // Use our custom error response
/// error::InternalError::from_response(
/// err, HttpResponse::Conflict().finish()).into()
/// })
/// })) /// }))
/// .route(web::post().to(index)) /// .route(web::post().to(index))
/// ); /// );