user93353
user93353

Reputation: 14039

Trapping a ConnectException in a JAX-WS webservice call

I am using JAX-WS 2.2.5 framework for calling WebServices. I want to identify the special case when the call fails because the Web Service is down or not accessible.

In some calls, i get a 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

In other places, I get ClientTransportException (class derived from 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

What's a good way to trap this error?

Should I use something like

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

or is there a better way of doing this?

Upvotes: 9

Views: 1778

Answers (2)

Luiz valença
Luiz valença

Reputation: 81

Maybe you'll want to treat UnknownHostException also!

        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();
        }

Upvotes: 1

ToYonos
ToYonos

Reputation: 16833

First you have to identify the top level Exception to catch. As you have pointed out, here it's WebServiceException.

What you can do next it's being more generic to avoid NullPointerException if 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;
        }
    }
}

Upvotes: 0

Related Questions