@@ -9,6 +9,7 @@ use std::pin::Pin;
9
9
use std:: task:: { Context , Poll } ;
10
10
11
11
use crate :: { mime, Mime } ;
12
+ use crate :: { Status , StatusCode } ;
12
13
13
14
pin_project_lite:: pin_project! {
14
15
/// A streaming HTTP body.
@@ -173,7 +174,9 @@ impl Body {
173
174
/// ```
174
175
pub async fn into_bytes ( mut self ) -> crate :: Result < Vec < u8 > > {
175
176
let mut buf = Vec :: with_capacity ( 1024 ) ;
176
- self . read_to_end ( & mut buf) . await ?;
177
+ self . read_to_end ( & mut buf)
178
+ . await
179
+ . status ( StatusCode :: UnprocessableEntity ) ?;
177
180
Ok ( buf)
178
181
}
179
182
@@ -221,7 +224,9 @@ impl Body {
221
224
/// ```
222
225
pub async fn into_string ( mut self ) -> crate :: Result < String > {
223
226
let mut result = String :: with_capacity ( self . len ( ) . unwrap_or ( 0 ) ) ;
224
- self . read_to_string ( & mut result) . await ?;
227
+ self . read_to_string ( & mut result)
228
+ . await
229
+ . status ( StatusCode :: UnprocessableEntity ) ?;
225
230
Ok ( result)
226
231
}
227
232
@@ -271,7 +276,7 @@ impl Body {
271
276
pub async fn into_json < T : DeserializeOwned > ( mut self ) -> crate :: Result < T > {
272
277
let mut buf = Vec :: with_capacity ( 1024 ) ;
273
278
self . read_to_end ( & mut buf) . await ?;
274
- Ok ( serde_json:: from_slice ( & buf) . map_err ( io :: Error :: from ) ?)
279
+ Ok ( serde_json:: from_slice ( & buf) . status ( StatusCode :: UnprocessableEntity ) ?)
275
280
}
276
281
277
282
/// Creates a `Body` from a type, serializing it using form encoding.
@@ -339,7 +344,7 @@ impl Body {
339
344
/// ```
340
345
pub async fn into_form < T : DeserializeOwned > ( self ) -> crate :: Result < T > {
341
346
let s = self . into_string ( ) . await ?;
342
- Ok ( serde_urlencoded:: from_str ( & s) ?)
347
+ Ok ( serde_urlencoded:: from_str ( & s) . status ( StatusCode :: UnprocessableEntity ) ?)
343
348
}
344
349
345
350
/// Create a `Body` from a file.
@@ -497,3 +502,31 @@ fn guess_ext(path: &Path) -> Option<Mime> {
497
502
None | Some ( _) => None ,
498
503
}
499
504
}
505
+
506
+ #[ cfg( test) ]
507
+ mod test {
508
+ use super :: * ;
509
+ use serde:: Deserialize ;
510
+
511
+ #[ async_std:: test]
512
+ async fn json_status ( ) {
513
+ #[ derive( Debug , Deserialize ) ]
514
+ struct Foo {
515
+ inner : String ,
516
+ }
517
+ let body = Body :: empty ( ) ;
518
+ let res = body. into_json :: < Foo > ( ) . await ;
519
+ assert_eq ! ( res. unwrap_err( ) . status( ) , 422 ) ;
520
+ }
521
+
522
+ #[ async_std:: test]
523
+ async fn form_status ( ) {
524
+ #[ derive( Debug , Deserialize ) ]
525
+ struct Foo {
526
+ inner : String ,
527
+ }
528
+ let body = Body :: empty ( ) ;
529
+ let res = body. into_form :: < Foo > ( ) . await ;
530
+ assert_eq ! ( res. unwrap_err( ) . status( ) , 422 ) ;
531
+ }
532
+ }
0 commit comments