【Spring Cloud】Feign呼叫異常觸發降級後如何捕獲異常

kamier發表於2023-01-31

一、問題背景

在Spring Cloud的微服務架構中,通常微服務之間透過feign/openfeign來進行http呼叫,並且啟用hystrix並配置降級策略fallback,可以在http呼叫異常時觸發降級,程式碼如下

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

@Component
public class ResourceFeignFallback implements ResourceFeign {

  @Override
  public Map<String, Object> 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<String, Object> resourceList();
}

@Component
@Slf4j
public class ResourceWebFeignFallbackFactory implements FallbackFactory<ResourceFeign> {

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

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

這樣就可以捕獲到http呼叫的異常資訊

相關文章