如何在Spring MVC中捕获所有未处理的异常(即没有现有@ExceptionHandler)?
2022-09-02 10:41:42
我想让 HandlerExceptionResolver 解析我没有通过注释显式捕获的任何异常。@ExceptionHandler
无论如何,我想在这些异常上应用特定的逻辑。例如,另外发送邮件通知或日志。我可以通过添加一个捕获来实现这一点,如下所示:@ExceptionHandler(Exception.class)
@RestControllerAdvice
public MyExceptionHandler {
@ExceptionHandler(IOException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Object io(HttpServletRequest req, Exception e) {
return ...
}
@ExceptionHandler(Exception.class)
public Object exception(HttpServletRequest req, Exception e) {
MailService.send();
Logger.logInSpecificWay();
//TODO how to continue in the "normal" spring way with HandlerExceptionResolver?
}
}
问题:如果我像这样添加,我可以捕获那些未处理的异常。@ExceptionHandler(Exception.class)
但我无法继续正常的工作流程来创建响应并自动设置HTTP状态代码。spring
HandlerExceptionResolver
ModelAndView
例如,如果有人尝试使用方法,则默认情况下spring将返回.但是有了一个,我会吞下这个标准的春天处理...POST
GET
405 Method not allowed
@ExceptionHandler(Exception.class)
那么,如何保留默认值,同时仍应用我的自定义逻辑呢?HandlerExceptionResolver