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

时间:2017-09-28 13:29:41

标签: java spring spring-mvc exception-handling

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

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

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

如何更改响应状态代码而不创建新的Exception,我只需要捕获DataIntegrityViolationException

1 个答案:

答案 0 :(得分:1)

你走两路。

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

private final ActorSystem actorSystem;
private final ExecutionContext executionContext;
private final RgsDataServiceServices rgsDataServiceServices;

@Inject
public AutoGateJob(ActorSystem system, ExecutionContext context, RgsDataServiceServices rgsDataServiceServices) {
  Logger.info("### create autojob");
  this.actorSystem = system;
  this.executionContext = context;
  this.rgsDataServiceServices = rgsDataServiceServices

  this.initialize();
}

<强> 2。使用ResponseEntity和异常

返回ResponseEntity。

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