[英]JAX-RS: Convert Response to Exception
我正在使用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)
}
JAX-RS API不支持將響應轉換為異常。 如果你檢查JerseyInvocation.convertToException()方法,你會發現在Jersey中它是一個簡單的開關,它將Response
狀態轉換為相應的Exception。
那么,你有兩個選擇:
webTarget.get(MyEntity.class)
。 當然,您可以在單個catch子句中捕獲所有WebApplicationException ,因為所有異常都會擴展它(例如,檢查BadRequestException )。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.