使用 @ControllerAdvice 和 @ResponseStatus 更改响应状态代码

Mel*_*ius 5 java spring exception-handling spring-mvc

我正在使用 spring mvc,处理异常我使用全局异常处理程序

@ControllerAdvice
public class GlobalControllerExceptionHandler {

    @ResponseStatus(value = HttpStatus.CONFLICT, reason = "Data integrity violation")
    @ExceptionHandler({DataIntegrityViolationException.class})
    public @ResponseBody AdminResponse handleConflict(DataIntegrityViolationException ex,HttpServletResponse httpServletResponse) {

        AdminResponse error = new AdminResponse ();

        httpServletResponse.setStatus(HttpStatus.CONFLICT.value());
        error.setStatus(Status.FAILURE);
        error.setErrorDescription(ex.getMessage());

        return error;
    }
Run Code Online (Sandbox Code Playgroud)

据我所知,注释 @ResponseStatus(value = HttpStatus.CONFLICT会将 repose 状态代码更改为HttpStatus.CONFLICT,但这不会发生。当我创建虚拟异常并注释这个虚拟异常@ResponseStatus然后抛出这个新异常时,GlobalControllerExceptionHandler捕获并处理异常并更改响应状态代码。

如何在不创建新异常的情况下更改响应状态代码,我只需要捕获 DataIntegrityViolationException

0ga*_*gam 1

你采取两条路。

1.使用@ResponseBody并返回自定义JSON字符串。

@ExceptionHandler(value = { HttpClientErrorException.class, HTTPException.class })
public @ResponseBody String checkHTTPException(HttpServletRequest req, Exception exception,
        HttpServletResponse resp) throws JsonProcessingException {

    ObjectMapper mapper = new ObjectMapper();
    CommonExceptionModel model = new CommonExceptionModel();

    model.setMessage("400 Bad Request");
    model.setCode(HttpStatus.BAD_REQUEST.toString());

    String commonExceptionString = mapper.writeValueAsString(model);

    return commonExceptionString;
}
Run Code Online (Sandbox Code Playgroud)

2.使用ResponseEntity和异常

返回响应实体。

ResponseEntity.status(exception.getStatusCode()).headers(exception.getResponseHeaders())
                            .body(exception.getResponseBodyAsString());
Run Code Online (Sandbox Code Playgroud)