I'm making a call to a REST service using the Spring WebClient, and I am trying to handle an io.netty.handler.timeout.ReadTimeoutException
which might happen from time to time:
try {
List<Asset> assets = client.searchAssets("some-type", assetCode);
// do sometihng
} catch (ReadTimeoutException ex) {
log.error("TimeoutException, can't wait no more :)");
}
However, when there is a Timeout Exception, this seems to be the exception I'm getting: WebClientRequestException
My question is, should I catch this WebClientRequestException
instead? How will I ever know if this was due to a ReadTimeoutException
?
In Spring's WebClient, exceptions from the underlying netty library (like io.netty.handler.timeout.ReadTimeoutException
) are often wrapped in a WebClientRequestException
. This is why you're seeing the WebClientRequestException
instead of the TimeoutException
.
When you catch a WebClientRequestException, you can check its cause to see if it is a TimeoutException. Here's an example of how to do that:
try {
// do something
} catch (WebClientRequestException ex) {
if (ex.getCause() instanceof TimeoutException) {
// timeout
} else {
// else
}
}
Please be aware that the timeout exception you may encounter is not the standard java.util.concurrent.TimeoutException
but rather the io.netty.handler.timeout.TimeoutException
. It's important to note that handling this exception will create a dependency (coupling) on the Netty library. If you modify the Spring WebClient configuration and switch the underlying library from Netty to another option, you must also update your code accordingly.