我使用array([[ 0.00000000e+00, 4.98000000e+02, 3.07646100e-03,
1.10000000e+01],
[ 1.00000000e+01, 5.00000000e+02, 4.09565100e-03,
2.10000000e+01]])
作为我的Jax-RS
框架。如果失败(即出现500错误),我希望能够从其余调用中提取错误消息。这样做的最佳方式是什么?
E.g。当我在REST
中拨打电话并收到错误时,我会收到500以下内容:
POSTMAN
如果呼叫失败,如何在我的代码中检索此信息?
答案 0 :(得分:1)
如果你要找的是解析那个:
该回复采用名为JSON
(JavaScript Object Notation)的文本格式
使用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();
}
}