1、第一步:创建一个springboot项目,比如在idea里面创建,直接下一步下一步即可,如图:
2、第二步:创建一个全局异常类,代码如下:@RestControllerAdvicepublic class ControllerExceptionHandleAdvice { private final static Logger logger = LoggerFactory.getLogger(ControllerExceptionHandleAdvice.class); @ExceptionHandler public String handler(HttpServletRequest req, HttpServletResponse res, Exception e) { }}
3、第三步:写入正确的返回码,比如返回200就是正常,代码如下:Map<String, String[]> parameterMap = req.getParameterMap();e.printStackTrace();if (res.getStatus() == HttpStatus.BAD_REQUEST.value()) { logger.info("修改返回状态值为200"); res.setStatus(HttpStatus.OK.value());}
4、第四步:自定义错误的状态码,根据异常类型添加,代码如下:if (e instanceof 鲍伊酷雪NullPointerException) { logger.error("代码00:" + e.getMessage(), e); return JSON.toJSONString(ResultEntity.fail("发生空指针异常"));} else { e.printStackTrace(); logger.error("代码99:" + e.getMessage()); return JSON.toJSONString(ResultEntity.fail("服务器代码发生异常,请联系管理员"));}
5、第五步:ResultEntity实体类代码如下:/** * @param string * @return */public static ResultEntity fail(String string) { ResultEntity resultEntity = new ResultEntity(); resultEntity.mesage = string; resultEntity.status = false; resultEntity.code = 500; return resultEntity;}
6、第六步:全部代码如下:@RestControllerAdvicepublic class 觊皱筠桡ControllerExceptionHand造婷用痃leAdvice { private final static Logger logger = LoggerFactory.getLogger(ControllerExceptionHandleAdvice.class); @ExceptionHandler public String handler(HttpServletRequest req, HttpServletResponse res, Exception e) { logger.info("Restful Http请求发生异常...{},{}",req.getRequestURL()); Map<String, String[]> parameterMap = req.getParameterMap(); e.printStackTrace(); if (res.getStatus() == HttpStatus.BAD_REQUEST.value()) { logger.info("修改返回状态值为200"); res.setStatus(HttpStatus.OK.value()); } if (e instanceof NullPointerException) { logger.error("代码00:" + e.getMessage(), e); return JSON.toJSONString(ResultEntity.fail("发生空指针异常")); } else { e.printStackTrace(); logger.error("代码99:" + e.getMessage()); return JSON.toJSONString(ResultEntity.fail("服务器代码发生异常,请联系管理员")); } }}
7、第七步:启动项目后,就会看到所有返回都被截获了,如图: