英文:
Why does Quarkus/Microprofile rest client Response.getEntity() return null?
问题
使用 Quarkus 3.0.3 Final
我有以下的 REST 客户端声明:
@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);
}
我还有一个错误映射器。
private String getBody(Response response) throws IOException {
response.getStringHeaders().forEach((s, strings) -> logger.info(s + ": " + strings.toString()));
// 是的,我知道这可以更好地处理,使用 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;
}
}
头部打印出来是
content-length: [148]
content-type: [application/json]
这让我相信有一个返回体,但是由于某种原因 response.getEntity()
返回了 null,当然,异常被捕获为 NullPointerException。但是响应应该是一个可以解析和处理下游错误代码的 JSON。
英文:
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.
答案1
得分: 1
这是因为getEntity()
仅返回内部Response
的实体对象,但如果你检查ResponseImpl
的源代码,你会发现还有entityStream
对象。
所以你应该首先使用另一种方法readEntity()
,例如:
var errorText = response.readEntity(String.class);
var errorResponse = objectMapper.readValue(errorText, ExceptionErrorResponse.class);
英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论