quarkusmicroprofilequarkus-rest-client

Why does Quarkus/Microprofile rest client Response.getEntity() return null?


using Quarkus 3.0.3 Final

I have the following rest client declaration:

@RegisterRestClient(configKey="my-api")
@RegisterProvider(value = ErrorMapper.class, priority = 50)
public interface SubscriberClient {
    @POST
    @Path("/v1")
    @Produces(MediaType.APPLICATION_JSON)
    MyResponse create(@HeaderParam("Authorization") String bearer, MyRequest request);
}

I also have in the error mapper.

private String getBody(Response response) throws IOException {

  response.getStringHeaders().forEach((s, strings) -> logger.info(s + ": " + strings.toString()));

  // YES I KNOW THIS CAN BE HANDLED BETTER WITH INSTANCEOF
  try (ByteArrayInputStream is = (ByteArrayInputStream) response.getEntity()) {
    byte[] bytes = new byte[is.available()];
    is.read(bytes, 0, is.available());
    String body = new String(bytes);
    return body;
  }
}

The headers print

content-length: [148]
content-type: [application/json]

Which leads me to believe there is a body returned, but for what ever reason response.getEntity() is returning null and of course the exception is caught as NullPointerException. But the response is supposed to be a Json that I can parse and handle the error code downstream.


Solution

  • That's because getEntity() returns only internal Response's entity object, but if you check source code of ResponseImpl you figure out there is also entityStream object.

    So you should use an alternative method readEntity() first, for instance

    var errorText = response.readEntity(String.class);
    var errorResponse = objectMapper.readValue(errorText, ExceptionErrorResponse.class);