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

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


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());    }}


You can use an ErrorDecoder and return your own exception from there and then use an exception handler. I had a similar problem and solved it like this:

public class ExceptionHandlerControllerAdvice extends ResponseEntityExceptionHandler...@ResponseStatus(BAD_REQUEST)@ExceptionHandler(HystrixRuntimeException.class)public ExceptionResponse handleHystrixRuntimeException(HystrixRuntimeException exception) {    if(exception.getCause() instanceof MyException) {        return handleMyException((MyException) exception.getCause());...

And then in my Configuration class for my FeignClient:

@Beanpublic ErrorDecoder feignErrorDecoder() {    return new ErrorDecoder() {        @Override        public Exception decode(String methodKey, Response response) {            return new MyException("timeout");        }    };}

That way you don't need multiple nested getCause()


If you want replace timeout exception throw by hystrix,you can write like this:

try {    testClient.timeoutTest();} catch (HystrixRuntimeException e) {    Throwable fallbackException = e.getFallbackException();    if (fallbackException.getCause().getCause() instanceof CustomException) {        log.info("customer exception!");    }}