1

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

2 回答 2

0

以下几行来自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

于 2018-02-21T17:15:23.350 回答
0

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

try {
  response = connection.call(request, endpoint);
} catch (SOAPException soapEx) {
  if(soapEx.getCause().getCause() instanceof SocketTimeoutException) {
    throw new TimeoutExpirationException(); //custom exception
  } else {
    throw soapEx;
  }
}
于 2018-03-06T13:51:42.900 回答