1. 方法返回 void

@FeignClient(name = "service-name")
public interface MyClient {
    @PostMapping("/api/operation")
    void doOperation();
}
  • 当接口返回状态码不是 2xx 时,Feign 会抛出异常

  • 抛出的是 FeignException或其子类(如 FeignException.NotFound等)

2. 方法返回 ResponseEntity

@FeignClient(name = "service-name")
public interface MyClient {
    @PostMapping("/api/operation")
    ResponseEntity<String> doOperation();
}
  • 无论接口返回什么状态码(200、400、404、500 等),Feign 都不会抛出异常

  • 调用方需要自己检查 ResponseEntity的状态码

  • 可以通过 responseEntity.getStatusCode()获取状态码

  • 可以通过 responseEntity.getBody()获取响应体

3. 示例对比

返回 void 的处理方式:

try {
    myClient.doOperation();
} catch (FeignException e) {
    int status = e.status();
    String error = e.getMessage();
    // 处理异常
}

返回 ResponseEntity 的处理方式:

ResponseEntity<String> response = myClient.doOperation();
if (!response.getStatusCode().is2xxSuccessful()) {
    int status = response.getStatusCodeValue();
    String body = response.getBody();
    // 处理非成功响应
}

4. 建议

  • 如果需要处理各种 HTTP 状态码,使用 ResponseEntity更灵活

  • 如果只关心成功情况,可以使用 void或自定义对象,让异常机制处理失败情况

  • 也可以通过配置 ErrorDecoder来自定义异常处理逻辑

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐