Netflix / Hystrix

Hystrix is a latency and fault tolerance library designed to isolate points of access to remote systems, services and 3rd party libraries, stop cascading failure and enable resilience in complex distributed systems where failure is inevitable.
24.08k stars 4.7k forks source link

How to throw a custom exception in a @FeignClient's fallback class? #2000

Open ZengRed opened 4 years ago

ZengRed commented 4 years ago

Hi, I'd like to throw a custom exception in a @FeignClient's fallback class then a springBoot's @ExceptionHandler will handle this custom exception: ` @Component public class HotelUserClientFallback implements HotelUserClient {

@Override
public DTO hello() {
    throw MyException("service is not avaiable...");
}

} `

But a HystrixRunTimeException is caught by @ExceptionHandler.

Any thing i can do to solve it?

pratikdandavate commented 4 years ago

I found another way to handle the exception in try-catch block that might help you instead of throwing an exception from fallback.

                     try {
                               //Code to handle
                     }
                     catch (Exception e) {
                // handling feign exception
                if (e instanceof HystrixRuntimeException) {
                    if (e.getCause() instanceof FeignException) {
                        Map<String, Object> handleFeignStatusException = handleFeignStatusException(
                                (FeignException) e.getCause(), response);
                        String reason = (String) handleFeignStatusException.get("message");
                        System.out.println(reason);
                        log.error("Error in : " + mappingData.get(i) + " Reason : " + reason);
                    }
                                  }
                               }
                          }
public Map<String, Object> handleFeignStatusException(FeignException e, HttpServletResponse response) {
        response.setStatus(e.status());
        return new JSONObject(e.contentUTF8()).toMap();
    }
alibbbian commented 2 years ago
@FeignClient(name = "${feign.client.mqtt-service:mqtt-service}", path = "/statistics"
        , fallbackFactory = MqttServiceStatisticsFeignClientFallBackFactory.class, configuration = YourConfiguration.class)

public class YourConfiguration {
       @Bean 
       public feign.codec.ErrorDecoder errorDecoder() {
              return new YourErrorDecoder();
       }
}

custum feign.codec.ErrorDecoder