1

我正在使用 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 成功块而不是错误块。在这种情况下,有什么方法可以让错误块执行吗?我不想抛出异常,因为它会在响应中发送整个堆栈跟踪。

4

1 回答 1

1

@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);
    }

}


于 2019-12-04T17:30:57.553 回答