30

I've initialized my restTemplate as follows:

HttpClient httpClient = HttpClientBuilder.create().build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
requestFactory.setConnectTimeout(1000);
requestFactory.setReadTimeout(1000);
restTemplate = new RestTemplate(requestFactory);

and I'm calling it like so:

restTemplate.getForEntity(someString, String.class, SomeHashmapWithURLParameters)

How do I handle both timeouts? I assume an exception will be thrown? If so which specific exception can I catch, in order to specifically handle just timeouts. I'm handeling other exceptions in different ways.

linuxdan
  • 4,476
  • 4
  • 30
  • 41

1 Answers1

60

In case of RestTemplate, when the request gets timed out, Spring will throw ResourceAccessException. Underlying exception under that instance will be java.net.SocketTimeoutException with message 'Read timed out'.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
  • 8
    ResourceAccessException is being thrown in case of Socket timeout or connection Timeout, so you need to check if ex.getCause is of type socket timeout exception. I have solved it by the following if statement: if (ex instanceof InterruptedException || (ex instanceof ResourceAccessException && ex.getCause() instanceof SocketTimeoutException)) { – amir bayan Jul 12 '19 at 14:12
  • @amirbayan is there any official spring documentation that explicitly note that RestTemplate throws a RAE with the underlying STE? the javadoc in the answer does not, unfortunately, and I need some official doc – Daniel Pop Aug 20 '20 at 07:45
  • @amirbayan why do you treat InterruptedException as timeout exception? – Simon Logic Jun 24 '21 at 12:23
  • since in case of timeout, the thread will be interrupted and it will throw that exception. from the description of Interrupted Exception: Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. – amir bayan Jun 25 '21 at 15:39