You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中是否需对ResponseEntity对象做空值检查?

Spring Boot中ResponseEntity是否需要空值检查再调用getBody()?
  • ResponseEntity对象本身不会为null:不管你用RestTemplate、Feign还是其他Spring官方客户端调用接口,哪怕返回4xx/5xx这类错误状态码,客户端都会返回一个包含对应状态码、响应头的ResponseEntity实例,不会返回null。所以你不需要先检查responseBody != null。

  • 但getBody()可能返回null:当接口返回204 No Content(无响应体),或者接口本身设计就是返回空体时,getBody()会返回null。所以拿到body之后,还是需要对Customer对象做非空检查。

  • 安全的代码示例:

ResponseEntity<Customer> responseEntity = customerClient.getCustomer(id);
// 先确认请求是否成功
if (responseEntity.getStatusCode().is2xxSuccessful()) {
    Customer customer = responseEntity.getBody();
    // 必须检查body是否为空
    if (customer != null) {
        // 处理业务逻辑
    } else {
        // 处理响应体为空的场景
    }
} else {
    // 处理请求失败的情况,比如404、500等
}

额外说明:如果你的客户端配置了自定义异常处理(比如Feign的ErrorDecoder),部分错误场景会直接抛出异常,不会返回ResponseEntity,这种情况下也不用考虑ResponseEntity为null的问题。

内容的提问来源于stack exchange,提问作者elvis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 02:05:55