SpringBoot - 过滤异常处理程序

Pan*_*nos 5 spring spring-boot spring-filter

我有一个弹簧启动应用程序。我有一个类来ControllerAdvice处理应用程序抛出的异常。

我创建了一个filter,我想用它来验证我所有请求的标头。当我从该过滤器抛出自定义异常时,它不会通过我的异常处理程序,而是使用默认的 Spring 错误控制。

有没有办法以我自己的方式处理过滤器的错误?

小智 1

您可以编写一个扩展的控制器BasicErrorController并编写一个具有@GetMapping如下注释的方法:

@RestController
public class FilterExceptionController extends BasicErrorController {

    private static final Logger LOGGER = LoggerFactory.getLogger(FilterExceptionController.class);

    public FilterExceptionController(){
        super(new DefaultErrorAttributes(),new ErrorProperties());
    }

    @GetMapping
    private <T> ResponseResult<T> serviceExceptionHandler(HttpServletRequest request) {
        Map<String,Object> body= getErrorAttributes(request,isIncludeStackTrace(request,MediaType.ALL));
        String message = String.valueOf(body.get("message"));
        body.forEach((k,v)->LOGGER.info("{} ==> {}",k,v));
        return RestResultGenerator.genError(500,"Filter Error Occurred, Message: [ "+message+" ]");
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试过滤器:

@WebFilter(filterName = "ipFilter",urlPatterns = "/*")
public class IpFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(!Arrays.asList(new String[]{"127.0.0.1"}).contains(servletRequest.getRemoteAddr())){
            throw new ServiceException(403,"ip forbid");
        }
    }

    @Override
    public void destroy() {

    }
}
Run Code Online (Sandbox Code Playgroud)

这是结果(但只得到异常消息而不是代码): 在此处输入图像描述