美文网首页spring 整合使用SpringBoot
SpringBoot全局异常处理器与Filter和Handler

SpringBoot全局异常处理器与Filter和Handler

作者: 小胖学编程 | 来源:发表于2021-06-08 09:51 被阅读0次

在Filter或者HandlerInterceptor抛出的异常能否被全局异常处理器捕获吗?本文将在实战的角度进行分析。

结论:filter抛出的异常全局异常捕获器不能捕获,但是HandlerInterceptor抛出的异常全局异常捕获器可以进行捕获。

1. 声明全局异常捕获器

import com.tellme.execption.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 测试全局异常捕获器
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public void SensitiveWordException(HttpServletRequest req, BusinessException e) {
        String code = e.getCode();
        String errMsg = e.getErrMsg();
        log.error(code + errMsg);
    }

}

2. 创建测试的Filter

@Component
public class TestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        throw new BusinessException("1001","测试全局捕获异常");
        //放行请求
//        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
image.png

文章详见:SpringBoot2.x整合Filter拦截器

当Filter抛出异常,全局异常处理器不能进行捕获!

3. 创建测试的HandlerInterceptor

SpringBoot2.x整合HandlerInterceptor拦截器(1-定义拦截器)

public class TestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        throw new BusinessException("1001","测试全局捕获异常");
    }
}
@Slf4j
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        log.info("加载拦截器[testInterceptor]");
        registry.addInterceptor(testInterceptor()).addPathPatterns("/**");
    }
    @Bean
    public TestInterceptor testInterceptor() {
        return new TestInterceptor();
    }
}

当项目启动后,拦截器抛出异常,全局异常捕获器是可以进行捕获的。

总结

本文涉及知识点:

  1. Filter和HandlerInterceptor加入到Spring容器的方法;
  2. 实现全局异常捕获器;
  3. Filter和HandlerInterceptor是否可以被全局异常捕获器进行捕获;

相关文章

网友评论

    本文标题:SpringBoot全局异常处理器与Filter和Handler

    本文链接:https://www.haomeiwen.com/subject/xzlxeltx.html