【Spring Cloud】Feign调用异常触发降级后如何捕获异常

一、问题背景

在Spring Cloud的微服务架构中,通常微服务之间通过feign/openfeign来进行http调用,并且启用hystrix并配置降级策略fallback,可以在http调用异常时触发降级,代码如下

@FeignClient(name = "resourceFeign", fallback = ResourceFeignFallback.class)
public interface ResourceFeign {
    @PostMapping("/resource/list")
    Map resourceList();
}

@Component
public class ResourceFeignFallback implements ResourceFeign {

  @Override
  public Map resourceList() {
    Map result = new HashMap<>();
    result.put("code", 500);
    result.put("msg", "请求异常");
    return result;
  }
}

但是这种方式在http调用异常时,会直接执行降级策略,而无法捕获到具体的异常信息,这种情况如何解决?

二、解决方法

所以我们通常使用另一种方式,通过配置fallbackFactory来捕获异常信息,代码如下

@FeignClient(name = "resourceFeign", fallbackFactory = ResourceFeignFallbackFactory.class)
public interface ResourceFeign {
    @PostMapping("/resource/list")
    Map resourceList();
}

@Component
@Slf4j
public class ResourceWebFeignFallbackFactory implements FallbackFactory {

    @Override
    public ResourceFeign create(Throwable throwable) {
        // 捕获异常
        log.error(throwable.getMessage());

        return new ResourceFeign() {
            @Override
            public Map resourceList() {
                  Map result = new HashMap<>();
                  result.put("code", 500);
                  result.put("msg", "请求异常");
                  return result;
            }
        };
    }
}

这样就可以捕获到http调用的异常信息

你可能感兴趣的:(【Spring Cloud】Feign调用异常触发降级后如何捕获异常)