Search code examples
javaspringtimeoutresttemplate

Common approach for handling of timeout and other IO exceptions with Spring Rest Template


Problem

I have about 40 methods that use RestTemplate to make HTTP calls. At this point of time I decided to create an error handler which will map RestTemplateException to my own exception(e.g. MyApplicationRestException).

Considered approaches

  1. Wrap all the calls with try/catch

    1.1 Disadvantage: should update all 40 methods. Easy to forget those try/catch in new methods

  2. org.springframework.web.client.ResponseErrorHandler

    2.1 Disadvantage: for some reason it catches only exceptions that have statusCode != null. So it can't handle timeouts.

  3. Introduce a new aspect that will catch all RestTemplateException and handle them properly. It resolves all disadvantages of previous solutions but I always implement aspects as a last choice.

Are there any better solutions?


Solution

  • Finally I've come up with aspect:

    @Aspect
    @Component
    public class RestCallsExceptionHandlingAspect {
    
        @AfterThrowing(pointcut = "execution(* eu.mypackage.RestClient.*(..))", throwing = "e")
        public void handle(Exception e) throws Throwable  {
            if (e instanceof RestClientException) {
                if (e instanceof HttpStatusCodeException) {
                    if (((HttpStatusCodeException)e).getStatusCode().is4xxClientError()) {
                        throw new TranslatableException(e, ValidationErrorGroup.COMMUNICATION_ERROR, CommonErrorCode.CLIENT_ERROR.name());
                    } else {
                        throw new TranslatableException(e, ValidationErrorGroup.COMMUNICATION_ERROR, CommonErrorCode.SERVER_ERROR.name());
                    }
                } else {
                    throw new TranslatableException(e, ValidationErrorGroup.COMMUNICATION_ERROR, CommonErrorCode.CORE_IO_ERROR.name());
                }
            }
            throw e;
        }
    }