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
Wrap all the calls with try/catch
1.1 Disadvantage: should update all 40 methods. Easy to forget those try/catch in new methods
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.
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?
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;
}
}