SpringBoot @ExceptionHandler 如何捕获 @WebFilter 的异常

yufei       1 年, 11 月 前       494

天下文章一大抄,#CSDN 上的答案几乎就是坑爹货,一旦对都是将异常信息 setrequest后再转发到自定义controller。

因此,错误的做法

将异常信息 setrequest后再转发到自定义controller。

正确的做法

抛出异常

@WebFilter(urlPatterns = "/*", filterName = "xxxFilter")
public class TestFilter implements Filter {

    // ........
    // ......

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        ServletResponse response = servletResponse;

        String token = request.getHeader("token");

        if (token == null || !token.equals("123")) {
          throw new BadRequestException("非法请求!");
        } else {
            filterChain.doFilter(request, response);
        }
    }
}

捕获方法

@RestController
@Slf4j
public class GlobalErrorController extends BasicErrorController {

    // ........
    // ........
    // ........

    @Override
    @RequestMapping
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        log.error("进入error处理器");
        Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
        if (throwable instanceof UtException) {
            UtException utException = (UtException) throwable;
            Integer statusCode = utException.getStatus().value();
            return new ResponseEntity(new BaseResponse<>(statusCode, utException.getMessage(), null), utException.getStatus());
        } else {
            return new ResponseEntity(new BaseResponse<>(500, "出现意料之外的错误", null), HttpStatus.valueOf(500));
        }
    }
}
目前尚无回复
简单教程 = 简单教程,简单编程
简单教程 是一个关于技术和学习的地方
现在注册
已注册用户请 登入
关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.