Search code examples
javaspringhystrixfeign

Can I throw a custom error if a hystrix-protected call times out?


I have a feign client with this external call:

@RequestMapping(method = RequestMethod.GET, value = "GetResourceA", consumes = "application/json")
@Cacheable("ResourceA")
List<Stop> getResourceA() throws MyOwnException;

And in my application.yml I have this setting:

hystrix:
  command:
    default:
      execution.isolation.thread.timeoutInMilliseconds: 1000
      fallback.enabled: false

Now if getResourceA times out, i.e. it takes more than one second to complete, I either get this:

com.netflix.hystrix.exception.HystrixRuntimeException: getResourceA timed-out and no fallback available

Or, if I define a fallback from which I throw my own exception, I get this:

com.netflix.hystrix.exception.HystrixRuntimeException: getResourceA timed-out and fallback failed.

Can I not throw my own exception from the fallback?

What if I wish to throw my own exception when the service is down? I would like to not have a fallback (because I have no reasonable value to return from the fallback), but instead throw my own error that I can catch and let the program resume. Can someone help me out with this?

Update after the answer from Ben:

So I tried the approach with catching HysterixRuntimeException and checking what caused it, but ended up with this ugly code:

try {
    getResourceA();
} catch (HystrixRuntimeException e) {
    if (e.getFailureType().name().equals("TIMEOUT")) {
        throw new MyOwnException("Service timed out");
    }
    throw e;
}

All that to be able to throw MyOwnException on a timeout. Surely there must be another way?


Solution

  • You should be able to get the exception you throw from your fallback by getting the cause of the HystrixRuntimeException

    So, to handle your custom exception, you can do this:

    try {
        getResourceA();
    } catch (HystrixRuntimeException e) {
        if (e.getCause() instanceof MyException) {
            handleException((MyException)e.getCause());
        }
    }