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

10-04 18:53