繁体   English   中英

Spring @ControllerAdvice 不起作用

[英]Spring @ControllerAdvice doesn't work

我想在我的 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();
}
}

您可以定义ControllerAdvice的基本包

使用ResponseEntityExceptionHandler扩展全局异常类。 例如, public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM