GWT Throwing exception to client
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.
Source
As the documentation states, the following conditions have to be fulfilled for an exception to be sent to the client:
- It has to extend
Exception
(note thatRuntimeException
does that). - It has to be serializable. In short: implement
Serializable
, have a no-args constructor and have all the fields serializable. - In your
*Service
interface you need to add athrows
declaration to the method that can throw the exception. Note that you don't need to add thethrows
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:
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);
}
On the client side
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);
Not sure why hilal's answer was accepted as it is completely false.
In order for the exceptions to reach the client's browser you must throw a checked exception that is Serializable
and defined in the service interfaces.
If your service implementation throws a RuntimeException
the web client will receive a generic 500 error messages as follows:
[WARN] Exception while dispatching incoming RPC call
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract my.module.shared.Result my.module.client.service.Service.doSomething() throws my.module.shared.exception.MyCheckedException' threw an unexpected exception: my.module.shared.exception.AuthzRuntimeException: some authz message
at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java:389)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:579)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:324)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
Caused by: my.module.shared.exception.AuthzRuntimeException: some authz message
at my.module.shared.Authz.doSomeCheck(Authz.java:101)
at my.module.server.ServiceImpl.doSomething(ServiceImpl.java:283)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:561)
... 22 more
[ERROR] 500 - POST /module/userService (127.0.0.1) 57 bytes
Request headers
Host: 127.0.0.1:8888
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://127.0.0.1:8888/foo.html?gwt.codesvr=127.0.0.1:9997
Cookie: worknet=7k8g41ulbl674dp865t180tji5
Connection: keep-alive
Cache-Control: no-cache
X-GWT-Permutation: HostedMode
X-GWT-Module-Base: http://127.0.0.1:8888/module/
Content-Type: text/x-gwt-rpc; charset=utf-8
Content-Length: 1076
Pragma: no-cache
Response headers
Content-Type: text/plain
(RequestCallbackAdapter.java:209) 2013-10-18 13:16:56,966 [WARN ] Fail ""
com.google.gwt.user.client.rpc.StatusCodeException: 500 The call failed on the server; see server log for details
at com.google.gwt.user.client.rpc.impl.RequestCallbackAdapter.onResponseReceived(RequestCallbackAdapter.java:209)
at com.google.gwt.http.client.Request.fireOnResponseReceived(Request.java:258)
at com.google.gwt.http.client.RequestBuilder$1.onReadyStateChange(RequestBuilder.java:412)
at sun.reflect.GeneratedMethodAccessor40.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:338)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:219)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:571)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:279)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:242)
at sun.reflect.GeneratedMethodAccessor37.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:293)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:547)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
at java.lang.Thread.run(Unknown Source)
GWT can only handle unchecked exceptions(which means sent from server to client) which are not serialized that extends from RuntimeException. I don't know what AlreadyActivatedError
is. If it is not RuntimeException it can't be sent to the client(browser)
Maybe also note that if your specific Exception does not have a standard constructor, the generic 500 error message will also be displayed because it is not possible to deserialize the exception. Sadly, the gwt compiler and dev-mode plugin will not always point this problem out explicitly.. (that's how i got here anyway)
So, in combination with what vinnyjames said (the exception must be Serializable and be defined in the (RPC) service's interface), i found that processing exceptions in gwt client code is not too complicated.
精彩评论