我正在尝试执行一些适用于代码中所有 @ExceptionHandler
的通用逻辑。我知道我可以编写一个 HandlerInterceptor
来拦截快乐路径。但是我想 Hook 到异常处理生命周期中,以便在呈现错误响应之前执行一些常见的逻辑,例如日志记录。
在 Spring Boot/Spring MVC 中有没有办法做到这一点?如果可能的话,我想避免为此目的编写一个 servlet 过滤器。
最佳答案
我有一个解决方案。这是关于使用 HandlerInterceptor.afterCompletion
方法。但是,documentation of this method 中有一行声明:
Note: Will only be called if this interceptor's preHandle method has successfully completed and returned true!
所以诀窍是同时实现 preHandle
并使其返回 true
。
现在我的拦截器看起来像这样:
@Component
public class MyInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// perform common logic here
}
}
但要注意的一件事是,如果您有一个拦截器链,并且在这个拦截器抛出异常之前有一个拦截器,则该拦截器将没有机会执行。因此,如果我们重新排序拦截器链,使 MyInterceptor
位于顶部,它将拦截所有请求。
关于java - Spring Boot 拦截所有异常处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48785878/