问题描述
我正在尝试执行一些适用于代码中所有 @ExceptionHandler
的通用逻辑.我知道我可以编写一个 HandlerInterceptor
来拦截快乐路径.但我想挂钩异常处理生命周期,以便在呈现错误响应之前执行一些常见逻辑,例如日志记录.
I am trying to perform some common logic that applies to all my @ExceptionHandler
s in code. I know I can write a HandlerInterceptor
to intercept happy paths. But I would like to hook into the exception handling lifecycle so that I can execute some common logic such as logging, before the error response is rendered.
无论如何要在 Spring Boot/Spring MVC 中执行此操作吗?如果可能,我想避免为此目的编写 servlet 过滤器.
Is there anyway to do this in Spring Boot / Spring MVC? I would like to avoid having to write a servlet filter for this purpose if possible.
推荐答案
我有一个解决方案.这是关于使用 HandlerInterceptor.afterCompletion
方法.但是,在 此方法的文档 指出:
I have a solution. It's about using HandlerInterceptor.afterCompletion
method. However, there is a line in the documentation of this method that states that:
注意:只有当这个拦截器的preHandle方法成功完成并返回true时才会被调用!
所以诀窍是同时实现 preHandle
并使其返回 true
.
So the trick is to also implement the preHandle
and make it return true
.
现在我的拦截器看起来像这样:
Now my interceptor looks like this:
@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
位于顶部,它将拦截所有请求.
One thing to be aware of though is that if you have a chain of interceptors and an interceptor before this one throws an exception, this interceptor won't get a chance to execute. So if we reorder the interceptor chain so that MyInterceptor
is right at the top, it will intercept all requests.
这篇关于Spring Boot 拦截所有异常处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!