Skip to content

Commit a9357ed

Browse files
authored
Merge pull request #163 from http-rs/status-codes-for-parsing
Body parse errors return status 422
2 parents bc99e4b + 22504ae commit a9357ed

File tree

1 file changed

+37
-4
lines changed

1 file changed

+37
-4
lines changed

src/body.rs

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use std::pin::Pin;
99
use std::task::{Context, Poll};
1010

1111
use crate::{mime, Mime};
12+
use crate::{Status, StatusCode};
1213

1314
pin_project_lite::pin_project! {
1415
/// A streaming HTTP body.
@@ -173,7 +174,9 @@ impl Body {
173174
/// ```
174175
pub async fn into_bytes(mut self) -> crate::Result<Vec<u8>> {
175176
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)?;
177180
Ok(buf)
178181
}
179182

@@ -221,7 +224,9 @@ impl Body {
221224
/// ```
222225
pub async fn into_string(mut self) -> crate::Result<String> {
223226
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)?;
225230
Ok(result)
226231
}
227232

@@ -271,7 +276,7 @@ impl Body {
271276
pub async fn into_json<T: DeserializeOwned>(mut self) -> crate::Result<T> {
272277
let mut buf = Vec::with_capacity(1024);
273278
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)?)
275280
}
276281

277282
/// Creates a `Body` from a type, serializing it using form encoding.
@@ -339,7 +344,7 @@ impl Body {
339344
/// ```
340345
pub async fn into_form<T: DeserializeOwned>(self) -> crate::Result<T> {
341346
let s = self.into_string().await?;
342-
Ok(serde_urlencoded::from_str(&s)?)
347+
Ok(serde_urlencoded::from_str(&s).status(StatusCode::UnprocessableEntity)?)
343348
}
344349

345350
/// Create a `Body` from a file.
@@ -497,3 +502,31 @@ fn guess_ext(path: &Path) -> Option<Mime> {
497502
None | Some(_) => None,
498503
}
499504
}
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

Comments
 (0)