Search code examples
javaexceptionsoaperror-handlingsoapexception

Throw timeout exception from SOAPException


I am trying to throw a timeout exception in the code below. I tried a simple condition but it's not the proper way. My question is how can I distinct the timeout exception from SOAPException?

URL endpoint = new URL(null,
    urlStr,
    new URLStreamHandler() {
      // The url is the parent of this stream handler, so must create clone
      protected URLConnection openConnection(URL url) throws IOException {
        URL cloneURL = new URL(url.toString());
        HttpURLConnection cloneURLConnection = (HttpURLConnection) cloneURL.openConnection();
        // TimeOut settings
        cloneURLConnection.setConnectTimeout(10000);
        cloneURLConnection.setReadTimeout(10000);
        return cloneURLConnection;
      }
    });

try {
  response = connection.call(request, endpoint);
} catch (SOAPException soapEx) {
  if(soapEx.getMessage().contains("Message send failed")) {
    throw new TimeoutExpirationException();
  } else {
    throw soapEx;
  }
}

Solution

  • After some hours of testing I found the proper way to distict the SOAPException from Timeout related exceptions. So the solution is to take the parent cause field of the exception and check if it's an instance of SocketTimeoutException.

    try {
      response = connection.call(request, endpoint);
    } catch (SOAPException soapEx) {
      if(soapEx.getCause().getCause() instanceof SocketTimeoutException) {
        throw new TimeoutExpirationException(); //custom exception
      } else {
        throw soapEx;
      }
    }