Spring @ControllerAdvice 不起作用

Spring @ControllerAdvice doesn't work

我想在我的 GlobalExceptionHandler class 的帮助下处理任何控制器抛出的所有异常。当我将以下代码添加到我的控制器时,它工作正常。但在这种情况下,我必须向所有控制器添加以下代码。但我不想在每个控制器中重复以下代码。

@ExceptionHandler({ FiberValidationException.class }) public String handleValidationException(HttpServletRequest req, Exception ex) { return ex.getMessage(); }

当我删除它们并使用我的 GlobalExceptionHandler class 时,它不处理 例外。

这是什么原因?我该如何解决?

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

您可以定义 ControllerAdvice 的基础包

使用 ResponseEntityExceptionHandler 扩展全局例外 class。例如public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

在我的例子中,我为我的函数入口参数指定了错误的异常,例如,我为 MissingFormatArgumentException 传递了 EntityNotFoundException 异常,所以我对此异常的响应始终是 500,并且它从未在我的 ControllerAdvice 中捕获。