Baffling Serde Deserialization Problem

I've got a lot of serde code working with HTTP requests but have somehow ran into something simple I can't figure out - because there's no error information.

Code:

    #[derive(Deserialize)]
    struct PositionResponse {
        positions: Positions,
    }

    #[derive(Deserialize)]
    struct Positions {
        position: Position,
    }

#[derive(Deserialize)]
pub struct Position {
    pub id: i64,
    pub symbol: String,
    pub quantity: f64,
    pub cost_basis: f64,
}

Response:

"{\"positions\":{\"position\":{\"cost_basis\":2137.21,\"date_acquired\":\"2024-06-17T13:45:27.304Z\",\"id\":921310,\"quantity\":10.00000000,\"symbol\":\"AAPL\"}}}"

Error message:

"Could not parse response body: error decoding response body"

With other deserialization issues, serde would give me a specific error - can't find field, etc. But there's nothing here, and I can't see anything wrong.

Where's the error message coming from? Doesn't look like serde.

And your example works in the playground.

I'm calling reqwest:blocking::Response::json. Should be doing the same thing.

The message comes from that call:

            r.json::<T>()
                .map_err::<String, _>(|e| format!("Could not parse response body: {}", e))

I just figured it out! I was calling reqwest::blocking::Client::post instead of get!

Error message... not too helpful.

It looks like the Display formatting for reqwest::Error does not print out the underlying source error, but the Debug formatting does. Or you can access it by using the .source() method.

2 Likes

Yes; this was nonintuitive.

P.S. I knew as soon as I explained the problem I'd see the solution. It's funny how that works.

I'm going to guess the intent was that Display would be shown to users as a response error while the Debug would be in the server log? Something something security?

1 Like

That makes perfect sense.

I just learned something about Rust conventions.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.