当前位置:   article > 正文

统一处理@FeignClient调用接口异常----原样抛出_feignclient异常处理

feignclient异常处理
第三方系统调用我方系统@FeignClient接口时报错 com.netflix.hystrix.exception.HystrixRuntimeException: WorkFlowTaskOperateService#processWorkFlowTaskSyncCallback(TaskProcessDTO) failed and no fallback available.

我方系统出现FeignException.

 第三方调用者抛出的异常:HystrixRuntimeException

一检查我们系统确实没有指定fallback和configuration,并且调用方开启了feign.hystrix.enabled: true

@FeignClient(value = "taxplan-workflow")

修改方法:

 

第三方调用在Application.java添加处理Feign异常的全局处理方法

  1. @Bean
  2. public Feign.Builder feignBuilder() {
  3. return Feign.builder().requestInterceptor(new RequestInterceptor() {
  4. @Override
  5. public void apply(RequestTemplate requestTemplate) {
  6. Map<String, String> customHeaders = WebUtils.getCustomHeaders();
  7. customHeaders.forEach((k, v) -> {
  8. requestTemplate.header(k, v);
  9. });
  10. }
  11. }).errorDecoder(new CustomErrorDecoder());
  12. }

这里使用了RequestInterceptor拦截器,可以定制请求头,如果不想定制,可以改为

return Feign.builder().errorDecoder(new CustomErrorDecoder());
 

实现ErrorDecoder接口,其中ExceptionCode是枚举类.

  1. public Exception decode(String methodKey, Response response) {
  2. if (response.status() >= 400 && response.status() <= 499) {
  3. return new BaseBizException(ExceptionCode.CALL_INNER_ERROR, "Client error.httpStatusCode:" + response.status());
  4. } else {
  5. if (response.status() >= 500 && response.status() <= 599 && response.body() != null) {
  6. try {
  7. String content = CharStreams.toString(new InputStreamReader(response.body().asInputStream(), StandardCharsets.UTF_8));
  8. Map responseBody = (Map) JSONObject.parseObject(content, Map.class);
  9. if (responseBody.containsKey("code")) {
  10. return new BaseBizException(responseBody.get("code").toString(), Objects.toString(responseBody.get("msg")));
  11. }
  12. } catch (Exception var5) {
  13. }
  14. }
  15. return new BaseBizException(ExceptionCode.CALL_INNER_ERROR);
  16. }
  17. }

ExceptionCode枚举类如下:可以自定义增加删除

  1. public enum ExceptionCode {
  2. ILLEGAL_STATE(4001, "非法访问"),
  3. PARAM_REQUIRED(4002, "参数不能为空"),
  4. PARAM_FORMAT_ILLEGAL(4003, "参数格式错误"),
  5. REQUEST_DATA_DUPLICATION(4004, "重复请求"),
  6. REQUEST_DATA_ERROR(4005, "请求数据错误"),
  7. REQUEST_DATA_NOT_MATCH(4006, "请求数据不一致"),
  8. RECORD_NOT_EXIST(5001, "记录不存在"),
  9. RECORD_EXISTED(5002, "记录已存在"),
  10. RECORD_ILLEGAL_STATE(5003, "数据异常"),
  11. BALANCE_NOT_ENOUGH(5103, "余额不足"),
  12. CALL_INNER_ERROR(5800, "调用内部服务接口异常"),
  13. THIRD_PART_ERROR(5801, "调用第三方接口异常"),
  14. SYSTEM_ERROR(9999, "系统异常");
  15. public final int code;
  16. public final String defaultMessage;
  17. private ExceptionCode(int code, String defaultMessage) {
  18. this.code = code;
  19. this.defaultMessage = defaultMessage;
  20. }
  21. }

 

参考:

1.Spring Cloud Feign 熔断机制填坑

2.探讨通过Feign配合Hystrix进行调用时异常的处理

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
  

闽ICP备14008679号