2

我在 try-catch 中有一些代码,在该代码中我调用了 Web 服务。在 Web 服务上我设置了超时。

我有两个 Web 服务调用,一个不花时间就可以正常工作,另一个花很长时间来响应问题不是这样,而是由于超时,它应该抛出 SocketTimeoutException,但它会抛出 PrivilegedActionException,并且在长堆栈状态后,它的显示原因是 SocketTimeoutException。

我故意让服务调用时间非常短以获取 SocketTimeoutException,但它给了我 PrivilegedActionException 作为主要异常。

我想捕获 SocketTimeoutException 并且我无法捕获 PrivilegedActionException 因为在代码级别它显示的 PrivilegedActionException 没有被这个 try catch 抛出。

我写了下面的代码来实现我的目标,但它不起作用

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
}

堆栈跟踪:

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
4

2 回答 2

1

你可以捕捉PrivilegedActionException,并调用getCause来获取SocketTimeoutExceptionSocketTimeoutException如果不是直接原因,可能需要一个 while 循环。

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

临时解决方案:

catch(Exception e){
    if(e instanceof PrivilegedActionException){
         //while loop here
    }
}
于 2015-03-25T04:05:26.300 回答
0

最好定义自己的异常类并执行所需的操作。

只需确保在抛出异常之前释放您在程序中使用的所有资源。

于 2015-03-25T04:17:40.523 回答