我正在使用JAX-RS客户端来使用REST API.我不想让JAX-RS抛出一堆异常,所以我自己检查Response对象.但有时候,我只关心某些状态代码,我希望JAX-RS 回退到默认行为并抛出一个实际异常(将由AOP建议处理).有一个简单的方法吗?
public void delete(long id) {
Response response = client.delete(id);
Response.Status status = Response.Status.fromStatusCode(response.getStatus());
if (status == Response.Status.OK) {
return;
}
if (status == Response.Status.NOT_FOUND) {
throw new TeamNotFoundException();
}
if (status == Response.Status.CONFLICT) {
throw new TeamHasAssignedUsersException();
}
// if status was internal server error or something similar,
// throw whatever exception you would throw at first place
// magic.throwException(response)
}
Run Code Online (Sandbox Code Playgroud)
JAX-RS API 不支持将响应转换为异常。如果你检查JerseyIncation.convertToException()方法,你会发现在 Jersey 中它是一个简单的开关,可以将Response状态转换为相应的异常。
所以,你有两个选择:
webTarget.get(MyEntity.class)如果您需要一个实体主体,您可以致电。当然,您可以在单个 catch 子句中捕获所有WebApplicationException ,因为所有异常都扩展了它(例如检查BadRequestException)。| 归档时间: |
|
| 查看次数: |
1300 次 |
| 最近记录: |