【问题标题】:Donot wrap exceptions of Feign client Fall back method with Hystrix RunTime Exception不要用 Hystrix RunTime Exception 包装 Feign 客户端 Fall back 方法的异常
【发布时间】:2020-09-23 00:03:54
【问题描述】:

Fallback 服务将 ProductNotFoundException 包装到 HystrixRunTimeException 中。 我想传播自定义异常,而不是包装到 HystrixRunTimeException 中。 下面是代码sn-p供参考:

@FeignClient(name = "service1", fallback = FallBackService1.class )
public interface FeignService1{
      String validateProducts(Product product);
}

class FallBackService1 implements FeignService1{
  @override
  public String validateProducts(Product product){
     throw new ProductNotFoundException("P119","Product not found");
  }
}

我已启用 feign.hystrix.enable = true。

请帮忙。我想按原样传播异常。我不希望它被包裹起来。

【问题讨论】:

    标签: spring-boot microservices spring-cloud-feign openfeign


    【解决方案1】:

    似乎不可能告诉 hystrix 不要将您的自定义异常包装在回退方法中。 您可以做的是创建您的自定义 ErrorDecoder 并从那里抛出您的自定义异常。在这种情况下,您的自定义异常应该实现com.netflix.hystrix.exception.ExceptionNotWrappedByHystrix 否则 hystrix 会将其包装成HystrixRuntimeException

    简单的例子。

    1. 使用 ErrorDecoder 实现创建 feign 配置。请注意,如果您不希望所有 FeignClient 都由同一个解码器处理,请不要使用 @Configuration 注解标记 FeignClient1Config。
    import feign.codec.ErrorDecoder;
    import org.springframework.context.annotation.Bean;
    
    public class FeignClient1Config {
    
        @Bean
        public ErrorDecoder customErrorDecoder() {
            return (methodKey, response) -> {
                throw new ProductNotFoundException("P119","Product not found for request " + response.request());
            };
        }
    }
    
    1. 你的假客户端应该是这样的
    @FeignClient(name = "service1", configuration = FeignClient1Config.class)
    public interface FeignService1{
          String validateProducts(Product product);
    }
    

    这种实现的缺点是FeignService1中的所有方法都会被同一个错误解码器处理。

    要克服它,您可以创建自己的 fallbackFactory 并将其作为属性添加到 @FeignClient(fallbackFactory = ...) 或者我最喜欢的解决方案是this 并且不要忘记实现 ExceptionNotWrappedByHystrix 类的异常。

    【讨论】:

      猜你喜欢
      • 2019-04-21
      • 2020-10-21
      • 2019-02-18
      • 2019-07-27
      • 2019-09-05
      • 2021-12-05
      • 1970-01-01
      • 2016-03-09
      • 1970-01-01
      相关资源
      最近更新 更多