Kong / unirest-java

Unirest in Java: Simplified, lightweight HTTP client library.
http://kong.github.io/unirest-java/
MIT License
2.61k stars 593 forks source link

ObjectMapper should not serialize to expected type on 400+ response code #335

Closed mdentremont closed 4 years ago

mdentremont commented 4 years ago

I'm using the latest Unirest, with the Jackson object mapper. I'm doing the following:

Expected:

Actual:

We probably should go directly to using the error class on 400+ status codes.

It is also annoying that when using .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);, Jackson treats JSON which has completely different fields than my POJO as a successful de-serialization. I'd like to just instruct JSON to treat all my POJO properties as required by default, but that doesn't appear to be an option.

ryber commented 4 years ago

The problem here is that by the time you get to ifFailure the response has already been parsed. What we would need is some form of .asEither(SuccessType.class, FailType.class) unless we want to take a breaking change. We could possibly also add some config options to the ObjectMapper.

One note,Jackson does have a required property on @JsonProperty, but it only works on @JsonCreator constructor properties.

mdentremont commented 4 years ago

Those options sound good to me. I did see the "required" stuff you mentioned, unfortunately I was hoping to just have all properties be "required" by default, unless they were flagged as "optional", oh well!

ryber commented 4 years ago

yea, I think it's really weird that Jackson hasn't enabled this as even an option

ryber commented 4 years ago

OK, I think I have a good solution that should not be a big breaking change to anyone or a major interface change. We will simply keep the raw body around when the response is >= 400, then it will be available for the .mapError and other post methods.

There are a couple of maybe negatives to this, 1) it still attempts to parse the body in a failure 2) It adds a little memory as we need to keep those strings around. Let me know if this looks reasonable to you https://github.com/Kong/unirest-java/commit/c1eec1ac14e2bbc89fb169f785b2fb352c2bf35e

mdentremont commented 4 years ago

That sounds good to me!

ryber commented 4 years ago

released in 3.4.04

mdentremont commented 4 years ago

Thanks!