能否在Spring项目中同时使用ResponseStatusException与@ControllerAdvice?
如何让@ControllerAdvice不捕获ResponseStatusException?
在Spring项目中,使用ResponseStatusException处理预期错误时,若保留@ControllerAdvice处理校验异常(如ConstraintViolationException、MethodArgumentNotValidException)及未预期错误,会遇到@ExceptionHandler(Exception.class)同时捕获ResponseStatusException的问题,以下是两种可行的解决方式:
方式一:添加精确匹配的ResponseStatusException处理器
利用Spring异常处理器精确优先匹配的特性,在@ControllerAdvice中添加专门处理ResponseStatusException的方法,直接重新抛出异常,交由Spring内置机制处理其响应:
@ExceptionHandler(ResponseStatusException.class) public void passThroughResponseStatusException(ResponseStatusException ex) { throw ex; } @ExceptionHandler(Exception.class) public ResponseEntity<String> lastDefender(Exception ex) { logger.error("Unhandled error occurred", ex); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); }
由于ResponseStatusException的处理器匹配优先级更高,会先被触发,重新抛出的异常会由Spring默认逻辑处理,不会进入通用的Exception处理器。
方式二:在通用处理器中排除ResponseStatusException
直接在@ExceptionHandler(Exception.class)方法内判断异常类型,若为ResponseStatusException则重新抛出,否则执行原有处理逻辑:
@ExceptionHandler(Exception.class) public ResponseEntity<String> lastDefender(Exception ex) { if (ex instanceof ResponseStatusException) { throw ex; } logger.error("Unhandled error occurred", ex); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); }
这种方式无需新增方法,仅通过简单的类型判断即可实现需求。
内容的提问来源于stack exchange,提问作者Christian Giebel
相关产品推荐
相关产品推荐

