linuxdan
linuxdan

Reputation: 4854

Using sping's restTemplate with a timeout, how do I detect a timeout?

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.

Upvotes: 34

Views: 53567

Answers (1)

Darshan Mehta
Darshan Mehta

Reputation: 30809

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'.

Upvotes: 61

Related Questions