当前位置: 首页 > news >正文

使用 @FeignClient 处理异常

使用 @FeignClient 处理异常

  • 前言
  • 一、使用全局异常处理自定义返回码
  • 二、使用http状态码
    • 2.1. 使用 Feign 的 fallback(降级)机制
    • 2.2. 使用try catch进行异常捕获
    • 2.3. 使用自定义错误解码器(实现ErrorDecoder接口)

前言

在使用 @FeignClient 调用服务时,您可以通过以下方式处理异常。


一、使用全局异常处理自定义返回码

使用该方式,服务端接口http状态码还是200
通用响应类

@Data public class RestResponse<T> implements Serializable { /** * 操作返回信息 */ private String msg; /** * 操作返回信息代码 */ private Integer code; /** * 返回具体数据 */ private T data; public RestResponse<T> success(T data) { this.setData(data); this.setCode(200); this.setMsg("操作成功"); return this; } public RestResponse<T> error(Integer code, String msg) { this.setCode(code); this.setMsg(msg); return this; } public RestResponse error() { return error(ResultEnum.UNKNOWN_ERR); } public RestResponse<T> error(String msg) { error(); this.msg = msg; return this; } public RestResponse<T> error(ResultEnum rsEnum) { return error(rsEnum.getCode(), rsEnum.getMessage()); } public RestResponse<T> success() { this.code = 200; this.msg = "操作成功"; return this; } public RestResponse<T> success(ResultEnum resultEnum, T data) { this.setCode(resultEnum.getCode()); this.setMsg(resultEnum.getMessage()); this.setData(data); return this; } public RestResponse<T> success(Integer code, String message, T data) { this.setCode(code); this.setMsg(message); this.setData(data); return this; } }

全局异常处理器

@Slf4j @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public RestResponse ExceptionHandler(Exception e) { log.error(e.getMessage(), e); return new RestResponse().error(500, "接口调用失败"); } // 可以捕获其他类型的异常 }

FeignClient 接口

@Service @FeignClient(contextId = "TestService", value = "test") public interface TestService { @PostMapping("/open") RestResponse<TestResult> test(@RequestBody TestForm form); }

调用时通过自定义code来判断是否调用成功

RestResponse<TestResult> resp = service.test(form); if (!"200".equals(resp.getCode())) { // 处理错误,抛异常或返回默认结果 throw new BusinessException(resp.getMessage()); } TestResult result = resp.getData();

二、使用http状态码

2.1. 使用 Feign 的 fallback(降级)机制

服务端异常返回非200状态码

@Slf4j @RestController @RequestMapping("/open") public class OpenController { @Autowired private ITestService service; @PostMapping("/test") public Object test(TestForm form) { try { service.test(form); return ResponseEntity.ok("成功"); } catch (Exception e) { log.error("失败", e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()); } } }

FeignClient 接口

@Service @FeignClient(contextId = "TestService", value = "test" fallback = MyFeignClientFallback.class) public interface TestService { @PostMapping("/open") TestResult test(@RequestBody TestForm form); }

MyFeignClientFallback自定义返回

@Component public class MyFeignClientFallback implements MyFeignClient { @Override public DataResponse getData() { // 这里返回默认值或 null return null; } }

2.2. 使用try catch进行异常捕获

服务端异常返回非200状态码

@Slf4j @RestController @RequestMapping("/open") public class OpenController { @Autowired private ITestService service; @PostMapping("/test") public Object test(TestForm form) { try { service.test(form); return ResponseEntity.ok("成功"); } catch (Exception e) { log.error("失败", e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()); } } }

FeignClient 接口

@Service @FeignClient(contextId = "TestService", value = "test") public interface TestService { @PostMapping("/open") TestResult test(@RequestBody TestForm form); }

客户端调用

try { TestResult res = testService.test(); // 处理正常逻辑 } catch (Exception e) { // 处理异常情况,比如记录日志,返回默认值等 log.error("Feign调用失败", e); }

2.3. 使用自定义错误解码器(实现ErrorDecoder接口)

服务端异常返回非200状态码

@Slf4j @RestController @RequestMapping("/open") public class OpenController { @Autowired private ITestService service; @PostMapping("/test") public Object test(TestForm form) { try { service.test(form); return ResponseEntity.ok("成功"); } catch (Exception e) { log.error("失败", e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()); } } }

自定义错误解码器

public class CustomErrorDecoder implements ErrorDecoder { @Override public Exception decode(String methodKey, Response response) { // 根据状态码返回不同的异常 if (response.status() == 404) { return new NotFoundException("Resource not found"); } else if (response.status() == 500) { return new InternalServerErrorException("Internal server error"); } return new FeignException("Unknown error"); } }

在Feign客户端配置中注入自定义错误解码器

@Configuration public class FeignConfig { @Bean public ErrorDecoder errorDecoder() { return new CustomErrorDecoder(); } }

FeignClient 接口引入自定义错误解码器

@Service @FeignClient(contextId = "TestService", value = "test", configuration = FeignConfig.class) public interface TestService { @PostMapping("/open") TestResult test(@RequestBody TestForm form); }
http://www.jsqmd.com/news/1161618/

相关文章:

  • 2026 淮安市洪泽区防水、防水公司推荐、屋面防水、楼顶防水、卷材防水、厂房屋面防水、办公楼屋面防水、屋面防水修缮公司哪家好?TOP5 权威推荐 + 避坑指南 - 万至防水
  • FanControl终极指南:让Windows电脑风扇安静又高效的5个秘诀
  • DeepSeek与通义千问性能实测对比:从推理速度、中文理解到成本控制的7大硬核维度解析
  • 2026年7月最新苏州卡地亚官方售后联系电话与客户服务中心网点地址 - 卡地亚服务中心
  • 深度对比:关键架构、数据湖、数据中台的区别、关联与选型逻辑
  • 探索图像识别在游戏自动化中的实战应用:Python实现连连看智能破解
  • C语言-文件操作-9
  • 选安提瓜护照前,先看懂这几点好处和机构门道 - GrowthUME
  • 镇江京口区黄金回收实体店实测测评|5 家合规商家实力横向对比,本地变现避坑指南 - 铂衡汇黄金珠宝
  • LinkSwift:9大网盘直链解析神器终极指南 - 免费获取真实下载地址的高效方案
  • AppleRa1n:iOS 15-16激活锁绕过终极指南,让被锁设备重获新生
  • DailyTech-20260709
  • 自动格式化失效?Cursor AI中Prettier不生效的7种隐性原因,今天必须解决!
  • 赣州6家黄金回收实地测评|亲身卖金全程对比,按交易流程打分排名 - 小路路在天舞
  • 天梭官方售后服务中心地址及热线电话实地考察报告+多信源验证(2026年7月更新) - 天梭服务中心
  • 从零开始设计梦想岛屿:Happy Island Designer 完全指南
  • 顺序表-线性表
  • Honey Select 2终极增强补丁:三步解决语言障碍与功能限制
  • 求推荐蒸汽涡街流量计品牌 3个核心问题帮你理清 - 信息热点
  • Grounding DINO
  • Unity VR曲面UI插件开发:从网格变形到交互适配的完整实现
  • 如何用Video2X将老旧视频一键修复成高清画质?完整教程指南
  • 2026三亚田独黄金回收深度盘点|本地正规门店筛查+真实行情计价+避坑全集 - 清月黄金回收
  • ChatGPT Canvas实时协作画布深度解密(企业级知识图谱搭建实录)
  • (15-4)
  • 【算法与数据结构】二分法及其应用
  • 2026长沙翡翠臻品合规回收实测:六区两市一县全域服务网络与透明变现权威指南 - 分享测评官
  • iOS 27家庭App AI摄像头:智能安防技术解析与实践指南
  • 致远协同管理软件,覆盖政企全场景的一体化 OA 协同办公平台
  • DDrawCompat深度解析:Windows系统下DirectDraw兼容性解决方案