Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to handle Deserialization error #447

Closed
cortopy opened this issue Nov 2, 2021 · 2 comments
Closed

Unable to handle Deserialization error #447

cortopy opened this issue Nov 2, 2021 · 2 comments

Comments

@cortopy
Copy link

cortopy commented Nov 2, 2021

Bug Report

Version

├── axum v0.2.8

Platform

Linux laptop 5.10.70-1-MANJARO #1 SMP PREEMPT Thu Sep 30 15:29:01 UTC 2021 x86_64 GNU/Linux

Crates

serde

Description

I'm using the JSON extractor to deserialize Body into a defined struct.

With the following code:

struct Foo { field1: String }

async fn handler(Json(payload): Json<Foo>) -> StatusCode {
    println!("payload = {:#?}", payload);

    StatusCode::NO_CONTENT
}

pub fn handle_error(error: BoxError) -> Result<impl IntoResponse, Infallible> {
    error!(?error, "Service error");
    
    // I'd like to be able to handle 400 errors here

    Ok((
        StatusCode::INTERNAL_SERVER_ERROR,
        Cow::from(format!("Unhandled internal error: {}", error)),
    ))
}

pub fn routes() -> Router<BoxRoute> {
    Router::new()
        .route("/healthz", get(|| async { "OK" }))
        .route("/", post(webhooks.layer(TraceLayer::new_for_http())))
        .handle_error(handle_error)
        .check_infallible()
        .boxed()
}

If I make the right request like

curl -X POST https://localhost
   -H 'Content-Type: application/json'
   -d '{"field1":"bar"}'

the handler gets called and all is fine.

However, if the request is not valid, like

curl -X POST https://localhost
   -H 'Content-Type: application/json'
   -d '{"random":"value"}'

the server will respond with a 400. This is to be expected, except handle_error does not get called

I expected handle_error to get the error so that I can handle the 400 response myself

@davidpdrsn
Copy link
Member

A request not matching an extractor is not considered an error in axum, so handle_error doesn't apply.

This wasn't very well explained in axum 0.2's documentation but have been improved in 0.3, which I'm hoping to release today. I recommend you read through error handling and extractor which hopefully makes things more clear. While the docs are using 0.3 there should be very few differences in those areas between 0.2 and 0.3.

Let me know if you have more questions.

@cortopy
Copy link
Author

cortopy commented Nov 7, 2021

All clear now. Thanks a lot @davidpdrsn

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants