-2

I'm trying to catch an exception that is responsible for a timeout when requesting a server, but I can't reproduce such a situation in my program. Therefore, I need to know the class of the exception and the error message.

I tried to reproduce the exception by sending requests to a mock server, but without success

root
  • 1
  • It is necessary to catch the timeout exception exactly waiting for a response from the server, and not connecting to it – root Aug 03 '23 at 08:38
  • You can create another API for testing and put an infinite loop inside an endpoint. – Diego Borba Aug 03 '23 at 08:41

1 Answers1

0

The type of exception thrown can depend on the library used for making the server request. If you're using the java.net package's HttpURLConnection, the typical exception to be thrown is a java.net.SocketTimeoutException when a read or accept times out.

If you're using a library such as Apache HttpComponents, OkHttp, or Spring's RestTemplate, the exceptions thrown may differ, but they will often wrap the underlying SocketTimeoutException.

In the case of Apache HttpComponents, the exception will be a org.apache.http.conn.ConnectTimeoutException if the connection times out, or org.apache.http.conn.SocketTimeoutException for a socket timeout.

If you're using OkHttp, a timeout will result in a java.net.SocketTimeoutException being thrown.

If you're using Spring's RestTemplate, a org.springframework.web.client.ResourceAccessException may be thrown, wrapping the underlying SocketTimeoutException.

Note that in all these cases, you'll want to handle not just timeouts but also general IOException cases that can occur due to network errors.

jaragone
  • 48
  • 1
  • 3
  • i am using HttpURLConnection of java.net package. The fact is that a SocketException is also thrown when the connection to the server timeout, how then to distinguish a timeout error when connecting to the server from a timeout error when waiting for a response from the server? – root Aug 03 '23 at 08:46
  • @root `SocketTimeoutException ` != `SocketException`. – user207421 Aug 03 '23 at 08:47
  • In the HttpURLConnection API, there is no built-in way to differentiate a connection timeout from a read timeout because both throw a SocketTimeoutException. The difference in timing and the phase in which the exception is thrown is the only way to distinguish between the two. If you need more granular control, you may need to use a more feature-rich HTTP client library. – jaragone Aug 03 '23 at 08:51