从 SOAPException 中抛出超时异常

Throw timeout exception from SOAPException

我试图在下面的代码中抛出超时异常。我尝试了一个简单的条件,但这不是正确的方法。 我的问题是如何区分超时异常和 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;
  }
}

以下几行来自call方法的公开jdk源代码。在代码中,他们只使用 Exception (也使用链接?评论)。我认为没有其他方法,除非 Oracle jdk 以不同的方式处理此问题。
您仍然可以尝试 if(soapEx.getCause() instanceof SomeTimeoutException)(不确定这是否有效)

            try {
                SOAPMessage response = post(message, (URL)endPoint);
                return response;
            } catch (Exception ex) {
                // TBD -- chaining?
                throw new SOAPExceptionImpl(ex);
            } 

如果要查看源码HttpSoapConnection

经过几个小时的测试,我找到了将 SOAPException 与超时相关异常区分开来的正确方法。所以解决方案是获取异常的父原因字段并检查它是否是 SocketTimeoutException.

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