在JAX-WS Web服务调用中捕获ConnectException

use*_*353 9 java web-services exception-handling jax-ws webservices-client

我正在使用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
Run Code Online (Sandbox Code Playgroud)

在其他地方,我得到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
Run Code Online (Sandbox Code Playgroud)

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

我应该使用类似的东西吗?

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

或者有更好的方法吗?

ToY*_*nos 0

首先,您必须确定Exception要捕获的最高级别。正如您所指出的,它就在这里WebServiceException

接下来你可以做的是更通用地避免NullPointerExceptionif getCause()returns null

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)