すべてを明確にするために、例外がシリアライズ可能である限り、サーバーからクライアントへのチェック済み(拡張)例外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);