[英]ResponseBuilder gives 200 OK HTTP response even for server error
我正在使用 javax.ws.rs.core.Response api 來構建響應並將響應從我的 Spring Boot 后端發送回前端。 我有一個控制器如下。
@GetMapping(value = "/details")
public Response getDetails() throws ServiceException {
try {
//logic to get details
return Response.status(Response.Status.OK).entity(details).build();
} catch (Exception e) {
log.error(e.getMessage());
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage).build();
}
}
但是即使在出現異常的情況下,我也得到 200 OK 作為瀏覽器/郵遞員中 HTTP 請求的響應狀態。 正因為如此,當出現異常時,ajax成功塊而不是錯誤塊被執行。 在這種情況下,有沒有辦法讓錯誤塊執行? 我不想拋出異常,因為它在響應中發送整個堆棧跟蹤。
@GetMapping
來自 spring mvc,而 spring-mvc 不符合 JAX-RS。 所以不要混合使用它們。 使用純 spring-mvc 或純 JAX-RS 。 您可以嘗試返回一個 spring-mvc ResponseEntity
(相當於 JAX-RS Response
):
@GetMapping(value = "/details")
public ResponseEntity getDetails() throws ServiceException {
try {
//logic to get details
return ResponseEntity.ok(details);
} catch (Exception e) {
log.error(e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.