Kong/unirest-java

API exceptions result in ParsingError when using GenericType<>

amra-s opened this issue · 1 comments

I get a parsing exception when receiving an error message for the following API call
unirest.get(someURL).asObject(GenericType<List>)

The parsing message looks like this

java.lang.RuntimeException: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type java.util.ArrayList<SomeClass> from Object value (token JsonToken.START_OBJECT)
at [Source: (String)"{ "message": "Internal Server Error"}"; line: 1, column: 1]

This is caused by the fact that unirest tries to parse the error message to the List object even though it receives a status of >= 400.

To Reproduce

unirest.get(someUrl) .queryString("fooNr", fooId) .asObject(new GenericType<List<SomeClass>>() { }) .mapBody(..... });

In my interceptor

@Override
public void onResponse(final HttpResponse<?> response, final HttpRequestSummary request, final Config config) {
    response.ifFailure(httpResponse -> {

        if (httpResponse.getStatus() == 404) {

            throw new NotFoundException(
                    "Not found " + httpResponse.getStatusText());
        }

        httpResponse.
                getParsingError().
                ifPresentOrElse(error -> {
                            throw error; #I don't expect a parsing error here if the API returns i.e. Status 404 'SomeClass with id 1234 does not exist'
                        },
                        () -> {
                            throw new ExternalServiceException(httpResponse.getStatusText(), httpResponse.getStatus());
                        });

    });           

Expected behavior
I would expect the behavior to be the same as when I make the following call
unirest.get(someURL).asObject(SomeClass)
which does not result in a parsing error but allows me map the errormessage to my ErrorClass.

Screenshots
If applicable, add screenshots to help explain your problem.

Environmental Data:

  • Java Version 21
  • Version 4.4.0

Additional context
Errorhandling works fine with Normal Classes but shows strange behavior with GenericType<>.

I wrote a test showing the behavior of the parsing exception. It throws in both asObject(Class) and in asObject(GenericType). which is indeed what I expected. Unirest will always attempt to parse the response even if its not a 200 response.