gpt4 book ai didi

java - 如何以良好的 Java 方式处理由 Exception 引起的问题

转载 作者:行者123 更新时间:2023-11-30 11:06:36 24 4
gpt4 key购买 nike

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

我有两个 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

最佳答案

您可以捕获PrivilegedActionException,然后调用getCause获取 SocketTimeoutException。如果 SocketTimeoutException 不是直接原因,则可能需要 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
}
}

关于java - 如何以良好的 Java 方式处理由 Exception 引起的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29247180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com