Can someone show to throw exception to client in GWT.
in my serviceasync interface i am doing this as well in my service interface
void ActivateUserAccount(String ActivationCode,AsyncCallback <Boolean> Callback) throws AlreadyActivatedError;
in my serverimpl;
i am doing this to throw an exception
public Boolean ActivateUserAccount(String ActivationCode) throws AlreadyActivatedError
{
....
throw new AlreadyActivatedError();
}
my exception is in the form:
public class AlreadyActivatedError extends Exception implements IsSerializable
{
public AlreadyActivatedError()
{
super();
}
}
Just to make everything clear: you can throw both checked (the ones extending Exception
) and unchecked (extending RuntimeException
) exceptions from the server to the client - as long as the exception is serializable. It is however recommended to throw checked exceptions, as they
represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files).
In contrast, unchecked exceptions
represent defects in the program (bugs) - often invalid arguments passed to a non-private method.
As the documentation states, the following conditions have to be fulfilled for an exception to be sent to the client:
Exception
(note that RuntimeException
does that).Serializable
, have a no-args constructor and have all the fields serializable.*Service
interface you need to add a throws
declaration to the method that can throw the exception. Note that you don't need to add the throws
declaration to the *Async
interface.Once you have that set up, you'll be able to handle the exception in the onFailure
method in your AsyncCallback
.
Some code to show all the pieces together, based on examples from the guide on the GWT site:
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;
}
}
@RemoteServiceRelativePath("stockPrices")
public interface StockPriceService extends RemoteService {
StockPrice[] getPrices(String[] symbols) throws DelistedException;
}
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);