只是为了说明一切:您可以将已检查(扩展 Exception)和未检查(扩展 RuntimeException)的异常从服务器抛出到客户端 - 只要异常是 serializable。但是建议抛出已检查的异常,因为它们
表示程序无法直接控制的区域中的无效条件(无效的用户输入、数据库问题、网络中断、缺少文件)。
相比之下,未经检查的异常
表示程序中的缺陷(错误) - 传递给非私有方法的参数通常无效。
Source
作为documentation states,必须满足以下条件才能向客户端发送异常:
- 它必须扩展
Exception(注意RuntimeException 会这样做)。
- 必须是serializable。简而言之:实现
Serializable,有一个无参数的构造函数,并且所有的字段都可以序列化。
- 在您的
*Service 接口中,您需要向可以抛出异常的方法添加throws 声明。请注意,您无需将throws 声明添加到*Async 接口。
设置完成后,您将能够在 AsyncCallback 中的 onFailure 方法中处理异常。
根据the guide on the GWT site 中的示例,一些代码将所有部分显示在一起:
DelistedException.java
public class DelistedException extends Exception implements Serializable {
private String symbol;
// Note the no-args constructor
// It can be protected so that only subclasses could use it
// (because if they want to be serializable too, they'll need
// a no-args constructor that calls the superclasses' no-args constructor...)
protected DelistedException() {
}
public DelistedException(String symbol) {
this.symbol = symbol;
}
public String getSymbol() {
return this.symbol;
}
}
StockPriceService.java
@RemoteServiceRelativePath("stockPrices")
public interface StockPriceService extends RemoteService {
StockPrice[] getPrices(String[] symbols) throws DelistedException;
}
StockPriceServiceAsync.java
public interface StockPriceServiceAsync {
void getPrices(String[] symbols, AsyncCallback<StockPrice[]> callback);
}
在客户端
AsyncCallback<StockPrice[]> callback = new AsyncCallback<StockPrice[]>() {
public void onFailure(Throwable caught) {
if (caught instanceof DelistedException) {
// Do something with it
} else {
// Probably some unchecked exception,
// show some generic error message
}
public void onSuccess(StockPrice[] result) {
// Success!
}
};
stockPriceService.getPrices(symbols, callback);