40.6. 捕获从远程服务返回的例外
概述
发出异步请求的消费者不会收到与同步请求时返回的异常。异步返回到消费者的任何例外都嵌套在 ExecutionException 异常中。服务抛出的实际异常存储在 ExecutionException 异常的 cause 字段中。
捕获异常
远程服务生成的异常是通过将响应传递给消费者业务逻辑的方法在本地引发。当消费者发出同步请求时,进行远程调用的方法会抛出异常。当消费者发出异步请求时,Response<T> 对象的 get () 方法会抛出异常。消费者不会发现在处理请求时遇到错误,直到尝试检索响应消息为止。
与 JAX-WS 框架生成的方法不同,Response<T> 对象的 get () 方法不会抛出用户建模的异常或通用 JAX-WS 异常。相反,它会抛出 java.util.concurrent.ExecutionException 异常。
获取例外详情
框架将来自远程服务返回的异常存储在 ExecutionException 异常的 cause 字段中。通过获取 cause 字段的值并检查存储的异常来提取远程异常的详细信息。存储的异常可以是任何用户定义的异常,也可以是通用 JAX-WS 异常之一。
示例
例 40.11 “使用轮询方法捕获例外” 演示了使用轮询方法捕获异常的示例。
例 40.11. 使用轮询方法捕获例外
package demo.hw.client;
import java.io.File;
import java.util.concurrent.Future;
import javax.xml.namespace.QName;
import javax.xml.ws.Response;
import org.apache.hello_world_async_soap_http.*;
public final class Client
{
private static final QName SERVICE_NAME
= new QName("http://apache.org/hello_world_async_soap_http",
"SOAPService");
private Client() {}
public static void main(String args[]) throws Exception
{
...
// port is a previously established proxy object.
Response<GreetMeSometimeResponse> resp =
port.greetMeSometimeAsync(System.getProperty("user.name"));
while (!resp.isDone())
{
// client does some work
}
try
{
GreetMeSometimeResponse reply = greetMeSomeTimeResp.get();
// process the response
}
catch (ExecutionException ee)
{
Throwable cause = ee.getCause();
System.out.println("Exception "+cause.getClass().getName()+" thrown by the remote service.");
}
}
}例 40.11 “使用轮询方法捕获例外” 中的代码执行以下操作:
在 try/catch 块中嵌套对 Response<T> 对象的 get () 方法的调用。
捕获 ExecutionException 异常。
从异常中提取 cause 字段。
如果消费者使用回调方法,用于捕获异常的代码将放置在提取服务响应的回调对象中。