【问题标题】:Trapping a ConnectException in a JAX-WS webservice call在 JAX-WS Web 服务调用中捕获 ConnectException
【发布时间】:2015-02-15 15:02:17
【问题描述】:

我正在使用 JAX-WS 2.2.5 框架来调用 WebServices。我想确定调用失败时的特殊情况,因为 Web 服务已关闭或无法访问。

在某些调用中,我得到一个 WebServiceException。

    catch(javax.xml.ws.WebServiceException e)
    {
        if(e.getCause() instanceof IOException)
            if(e.getCause().getCause() instanceof ConnectException)
                 // Will reach here because the Web Service was down or not accessible

在其他地方,我得到 ClientTransportException(从 WebServiceException 派生的类)

    catch(com.sun.xml.ws.client.ClientTransportException ce)
    {

         if(ce.getCause() instanceof ConnectException)
              // Will reach here because the Web Service was down or not accessible

捕获此错误的好方法是什么?

我应该使用类似的东西

    catch(javax.xml.ws.WebServiceException e)
    {
        if((e.getCause() instanceof ConnectException) || (e.getCause().getCause() instanceof ConnectException))
         {
                   // Webservice is down or inaccessible

或者有更好的方法吗?

【问题讨论】:

    标签: java web-services exception-handling jax-ws webservices-client


    【解决方案1】:

    首先,您必须确定要捕获的顶级Exception。正如您所指出的,这里是WebServiceException

    如果getCause() 返回null,您接下来可以做的是更通用地避免NullPointerException

    catch(javax.xml.ws.WebServiceException e)
    {
        Throwable cause = e; 
        while ((cause = cause.getCause()) != null)
        {
            if(cause instanceof ConnectException)
            {
                // Webservice is down or inaccessible
                // TODO some stuff
                break;
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      也许您还想处理 UnknownHostException!

              Throwable cause = e.getCause();
      
              while (cause != null)
              {
                  if (cause instanceof UnknownHostException)
                  {
                      //TODO some thing
                      break;
                  }
                  else if (cause instanceof ConnectException)
                  {
                      //TODO some thing
                      break;
                  }
      
                  cause = cause.getCause();
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多