java Spring@ControllerAdvice不起作用
我想在GlobalExceptionHandler类的帮助下处理任何控制器引发的所有异常。当我向控制器中添加以下代码时,它工作正常。但在这种情况下,我必须向所有控制器添加以下代码。但我不想在每个控制器中重复以下代码
@ExceptionHandler({ FiberValidationException.class })
public String handleValidationException(HttpServletRequest req, Exception ex)
{
return ex.getMessage();
}
当我删除它们并使用GlobalExceptionHandler类时,它不会处理 例外
原因是什么?我怎么能修好它
@ControllerAdvice
@EnableWebMvc
public class GlobalExceptionHandler {
private static final Logger LOG = Logger.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler({ FiberValidationException.class })
public String handleValidationException(HttpServletRequest req, Exception ex) {
LOG.error("FiberValidationException handler executed");
return ex.getMessage();
}
@ExceptionHandler({ ChannelOverflowException.class })
public String handleOverflowException(HttpServletRequest req, Exception ex) {
LOG.error("ChannelOverflowException handler executed");
return ex.getMessage();
}
}
# 1 楼答案
用
ResponseEntityExceptionHandler
扩展全局异常类。e、 g.public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
# 2 楼答案
您可以定义ControllerAdvice的基本包
# 3 楼答案
在我的例子中,我的函数入口参数被指定为错误的异常,例如,我为MissingFormatArgumentException传递了EntityNotFoundException异常,因此我对该异常的响应始终为500,并且它从未在我的ControllerAdvice中被捕获