易妖游戏网
您的当前位置:首页springboot 2 处理全局异常 及 404 4xx错误的异常捕获

springboot 2 处理全局异常 及 404 4xx错误的异常捕获

来源:易妖游戏网

1. 全局异常的处理, 由于网上相关的说明太多,  相关说明不在赘述.

    @ExceptionHandler(value = Exception.class)
    public ResponseData onException(HttpServletRequest request, Exception e){
        logger.error("", e);
        
        //自行的业务数据返回
        return this.getResponse(null, e);
    }

所在的处理类加上注解:

@ControllerAdvice
@ResponseBody

- - - -> 这样的话, 是可以处理代码中抛出的异常. 但是不会处理接管404之类的处理.

 

2. 404(请求路径错误), 403(请求)等错误的处理

springboot默认是由BasicErrorController来处理的, 返回对应的错误页面. 这显示不是我们想要的!

新建一个controller来接管错误处理

@Controller

借助默认异常处理的controller

    @Autowired
    private BasicErrorController basicErrorController;

添加方法, 接管/error的处理(由于我们用的是精确匹配, 所以会覆盖系统默认的处理)

    @RequestMapping(value = "/error", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object error(HttpServletRequest request, HttpServletResponse response){
        //定义为正常返回
        response.setStatus(HttpStatus.OK.value());
        
        //获取异常返回
        ResponseEntity<Map<String, Object>> errorDetail = basicErrorController.error(request);
        
        //自行组织返回数据
        return  responseInterceptor.getResponse(errorDetail.getBody(), new Exception("请求错误"));
    }

想要的信息全在里面

----> 也可以配置springboot让404抛出异常交由@ExceptionHandler, 个人不推荐, 会禁用add-mappings.

因篇幅问题不能全部显示,请点此查看更多更全内容