我想在我的 GlobalExceptionHandler 类的帮助下处理任何 Controller 抛出的所有异常。当我将以下代码添加到我的 Controller 时,它工作正常。但在这种情况下,我必须向所有 Controller 添加以下代码。但我不想在每个 Controller 中重复以下代码。
@ExceptionHandler({ FiberValidationException.class })
public String handleValidationException(HttpServletRequest req, Exception ex)
{
返回 ex.getMessage();
}
当我删除它们并使用我的 GlobalExceptionHandler 类时,它不处理 异常(exception)情况。
这是什么原因?我该如何解决?
@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();
}
}
最佳答案
使用 ResponseEntityExceptionHandler
扩展您的全局异常类。例如公共(public)类 GlobalExceptionHandler 扩展了 ResponseEntityExceptionHandler {
关于java - Spring @ControllerAdvice 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44499141/