Skip to content

Commit 7f4e975

Browse files
committed
Use serde_json::Error::is_data() to distinguish error kinds
1 parent e238395 commit 7f4e975

File tree

1 file changed

+10
-16
lines changed
  • crates/handlers/src/compat

1 file changed

+10
-16
lines changed

crates/handlers/src/compat/mod.rs

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -53,11 +53,8 @@ pub enum MatrixJsonBodyRejection {
5353
#[error("Failed to read request body")]
5454
BytesRejection(#[from] BytesRejection),
5555

56-
#[error("Body is not a valid JSON document")]
57-
NotJson(#[source] serde_json::Error),
58-
59-
#[error("Request body has invalid parameters")]
60-
BadJson(#[source] serde_json::Error),
56+
#[error("Invalid JSON document")]
57+
Json(#[from] serde_json::Error),
6158
}
6259

6360
impl IntoResponse for MatrixJsonBodyRejection {
@@ -92,15 +89,15 @@ impl IntoResponse for MatrixJsonBodyRejection {
9289
status: StatusCode::BAD_REQUEST,
9390
},
9491

95-
Self::NotJson(_) => MatrixError {
96-
errcode: "M_NOT_JSON",
97-
error: "Body is not a valid JSON document",
92+
Self::Json(err) if err.is_data() => MatrixError {
93+
errcode: "M_BAD_JSON",
94+
error: "JSON fields are not valid",
9895
status: StatusCode::BAD_REQUEST,
9996
},
10097

101-
Self::BadJson(_) => MatrixError {
102-
errcode: "M_BAD_JSON",
103-
error: "JSON fields are not valid",
98+
Self::Json(_) => MatrixError {
99+
errcode: "M_NOT_JSON",
100+
error: "Body is not a valid JSON document",
104101
status: StatusCode::BAD_REQUEST,
105102
},
106103
};
@@ -138,11 +135,8 @@ where
138135

139136
let bytes = Bytes::from_request(req, state).await?;
140137

141-
// We first parse it as a JSON value so that we can distinguish between
142-
// invalid JSON documents and invalid requests
143-
let value: serde_json::Value =
144-
serde_json::from_slice(&bytes).map_err(MatrixJsonBodyRejection::NotJson)?;
145-
let value = serde_json::from_value(value).map_err(MatrixJsonBodyRejection::BadJson)?;
138+
let value: T = serde_json::from_slice(&bytes)?;
139+
146140
Ok(Self(value))
147141
}
148142
}

0 commit comments

Comments
 (0)