dxps / fullstack-rust-axum-dioxus-rwa

A RealWorld app implementation as a fullstack Rust project using Axum (back-end) and Dioxus (front-end).
MIT License
80 stars 6 forks source link

Respond with a JSON in case of initial request body deserialization issues #8

Closed dxps closed 1 year ago

dxps commented 1 year ago

By default, in cases where the request body can't be deserialized as JSON, the response code is 422 (Unprocessable Entity), but the body is a text (explicitly declared also by the response's content-type header with value text/plain; charset=utf-8:

Failed to deserialize the JSON body into the target type: missing field `password` at line 5 column 3

A proper response of such an HTTP API would be a JSON with an error attribute, at minimum.

dxps commented 1 year ago

Solved in 0086b81e8c0ab1b169f12fb4fcd6dfdc526bd5d7.

The decision is to use a custom extractor (named InputJson just to have a clear distinction with the axum::Json or any serde related json parts).

Any handler would have to use it (that is InputJson instead of Json as it was before), like this:

pub async fn login_user(
    State(state): State<Arc<AppState>>,
    InputJson(input): InputJson<LoginUserInput>,
) -> impl IntoResponse {

image