springboot 怎么设置Status Code、

 时间:2026-02-16 06:26:25

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

springboot 怎么设置Status Code、

2、第二步:创建一个全局异常类,代码如下:

@RestControllerAdvice


public 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、第六步:全部代码如下:

@RestControllerAdvice


public class ControllerExceptionHandleAdvice {
   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占用率
  • 如何高效备考国际贸易实务之计算题
  • 【校园指南】云南大学呈贡校区之新生查成绩篇
  • 热门搜索
    考证大全 科技小制作大全简单 装修效果图大全 高血脂怎么办 大全集团 磊科路由器怎么设置 朱迅最近身体怎么样 纳兰性德简介 抗日电视剧大全 项目计划书怎么写