只是为了让一切清楚:只要异常是可序列化Exception
的,您就可以将已检查(扩展的)和未检查的(扩展RuntimeException
)异常从服务器抛出到客户端。但是,建议抛出已检查的异常,因为它们
表示程序无法直接控制的区域中的无效条件(无效的用户输入、数据库问题、网络中断、缺少文件)。
相反,未经检查的异常
表示程序中的缺陷(错误)——通常是传递给非私有方法的无效参数。
来源
如文档所述,必须满足以下条件才能将异常发送给客户端:
- 它必须扩展
Exception
(注意这样RuntimeException
做)。
- 它必须是可序列化的。简而言之:实现
Serializable
,有一个无参数的构造函数,并且所有的字段都可以序列化。
- 在您的
*Service
界面中,您需要向throws
可以引发异常的方法添加声明。请注意,您不需要将throws
声明添加到*Async
接口中。
设置完成后,您将能够onFailure
在AsyncCallback
.
根据GWT 网站上的指南中的示例,一些代码将所有部分一起显示:
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);