Search code examples
javaexceptionsocket-timeout-exception

How to handle cause by Exception in a good Java way


I have some code in try-catch and in that code I am calling web service.On web service I have set timeout.

I have two web service call one taking no time its working fine and another one taking long to respond problem is not that but because of the time out it should throw SocketTimeoutException but its throwing PrivilegedActionException and after a long stack stace its showing cause by SocketTimeoutException.

I have intentionally put service call time very short to get SocketTimeoutException but its giving me PrivilegedActionException as a primary Exception.

I want to catch SocketTimeoutException and I'm not able to catch PrivilegedActionException becuase at the code level its showing PrivilegedActionException has not been thrown by this try catch.

I have written below code for achieve my goal but it's not working

try {
  //some code here for service call
}catch(SocketTimeoutException e)
{
  //not able to come here even though cause of the PrivilegedActionException is SocketTimeoutException 
}
catch(Exception e)
{
  //directly coming here OF COURSE
}

stacktrace:

java.security.PrivilegedActionException: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Message send failed
com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: java.security.PrivilegedActionException: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Message send failed

Solution

  • you can catch PrivilegedActionException, and call getCause to get SocketTimeoutException. Maybe a while loop is needed if SocketTimeoutException is not a direct cause.

    try{
    
    }catch(PrivilegedActionException e){
        Throwable tmp = e;
        while(tmp != null){
            if(tmp instanceof SocketTimeoutException){
                SocketTimeoutException cause = (SocketTimeoutException) tmp;
                //Do what you need to do here.
                break;
            }
            tmp = tmp.getCause();
        }
    }
    

    Temporary solution:

    catch(Exception e){
        if(e instanceof PrivilegedActionException){
             //while loop here
        }
    }