我有一个API,当我通过邮递员调用它时,它会对以下情况给出以下响应:
案例1:状态代码:200
{"success": "student record is present",
"error": null}
案例2:状态代码:422
{"success": null,
"error": "studentname should not contain numerics"}
我想通过使用quarkus/java项目的微文件restclient来实现两个案例的相同结果。因此创建了以下类
Java DTO类:
public class StudentResponse{
private String success;
private String error;
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
@Override
public String toString() {
return "StudentResponse [success=" + success + ", error=" + error + "]";
}
}
Rest客户端类:
包com.tatagital.rest.service;
@RegisterRestClient(configKey = "student-client-api")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public interface StudentService {
@POST
@Path("/checkStudent")
StudentResponse checkStudent(@RequestBody StudentCheck studentCheck);
}
最后,我通过应用程序对其进行了测试,对于案例1,我收到了状态代码为200的响应体。但对于案例2,由于状态代码为422,异常被抛出并得到处理,但在异常对象中我们有响应对象,在它内部我们有响应实体。此响应实体为null,甚至studentResponse也为null。我想在422状态代码的情况下获得微文件rest客户端的错误消息(json响应(。有实现这一目标的方法/建议吗?
编辑
您还可以通过在application.properties中添加resteasy.original.webapplicationexception.behavior=true
来从DefaultResponseExceptionMapper实现相同的行为。
当此选项为false
时,DefaultResponseExceptionMapper会包装WebApplicationException,并根据HTTP状态代码返回异常,例如
} else if (e instanceof BadRequestException) {
return new ResteasyBadRequestException((BadRequestException)e);
}
它不包含来自响应的实体。
如果您启用原始行为,则异常将按原样返回,并且响应实体可供您读取。
wae.getResponse().readEntity(StudentResponse.class);
在状态代码的情况下>400抛出一个WebApplicationException
,它包含一个Response对象,但由DefaultResponseExceptionMapper
处理。
创建一个自定义异常映射程序,并抛出一个仅包含响应的WebApplicationException
public class HttpExceptionMapper implements ResponseExceptionMapper<Throwable> {
@Override
public Throwable toThrowable(Response response) {
throw new WebApplicationException(response);
}
}
使用适当的注释将映射程序注册到您的rest客户端@RegisterProvider(HttpExceptionMapper.class)
并且您将能够读取响应中的实体
StudentResponse studentResponse;
try {
studentResponse = checkStudent(studentCheck);
} catch(WebApplicationException wae) {
studentResponse = wae.getResponse().readEntity(StudentResponse.class);
}
不幸的是,Microprofile客户端不支持此功能。然而,这听起来是一个有用的功能,所以你介意在Quarkus问题跟踪器中打开一个问题吗?