springboot 怎么设置Status Code、

 时间:2024-10-13 19:43:21

1、第一步:创建一个springboot项目,比如在idea里面创建,直接下一步下一步即可,如图:

springboot 怎么设置Status Code、

2、第二步:创建一个全局异常类,代码如下:@RestControllerAdvicepublic class ControllerExceptionHandleAdvice { private final static Logger logger = LoggerFactory.getLogger(ControllerExceptionHandleAdvice.class); @ExceptionHandler public String handler(HttpServletRequest req, HttpServletResponse res, Exception e) { }}

springboot 怎么设置Status Code、

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());}

springboot 怎么设置Status Code、

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("服务器代码发生异常,请联系管理员"));}

springboot 怎么设置Status Code、

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;}

springboot 怎么设置Status Code、

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("服务器代码发生异常,请联系管理员")); } }}

springboot 怎么设置Status Code、

7、第七步:启动项目后,就会看到所有返回都被截获了,如图:

springboot 怎么设置Status Code、
  • 学生哪些阶段需要进行谈心谈话?
  • 海水的组成为什么有恒定性
  • 怎么看cpu占用率
  • 如何高效备考国际贸易实务之计算题
  • 【校园指南】云南大学呈贡校区之新生查成绩篇
  • 热门搜索
    关于科普知识的手抄报 反对邪教的手抄报 端午节的手抄报 简单 法制安全手抄报内容 中秋节手抄报大全 艺术手抄报 关于科技节的手抄报 环境手抄报内容 61儿童节手抄报 小学生电子手抄报