我正在使用 Jax-RS
作为我的REST
框架。如果失败(即出现 500 错误),我希望能够从 rest 调用中提取错误消息。最好的方法是什么?
例如。当我调用 POSTMAN
时并得到一个错误我得到以下500:
{
"reason": "No data retrieved for GET call",
"response": "failure"
}
如果调用失败,如何在我的代码中检索此信息?
最佳答案
如果您正在寻找的是解析:
该响应采用名为 JSON
的文本格式。 (JavaScript 对象表示法)
使用 JSON
解析库如GSON
String json = //..... get the api response as a String ....
APIResponse response = new Gson().fromJson(json, APIResponse.class);
使用
ApiResponse
看起来像:public class APIResponse {
public String reason;
public String response;
public void setReason(String reason) {
this.reason = reason;
}
public String getReason() {
return this.reason;
}
public void setReason(String reason) {
this.response = response;
}
public String getResponse() {
return this.response;
}
}
另一方面,如果这是来自您的 API 的响应并且您希望处理它:请查看 JAX-RS Exception Handling
您可以实现
ExceptionMapper
界面:public interface ExceptionMapper<E extends Throwable> {
Response toResponse(E exception);
}
并注册一个
@Provider
处理异常:@Provider
public class EntityNotFoundMapper implements ExceptionMapper<Exception> {
public Response toResponse(Exception e) {
// Do some logic like log an error
return Response.status(Response.Status.NOT_FOUND).build();
}
}
关于java - 贾克斯-RS : Getting error message from REST call?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46665324/