如何在GWT RPC中触发onFailure?

时间:2011-06-06 11:01:47

标签: gwt

  

可能重复:
  StatusCodeException Vs. RuntimeException in GWT

如果会话在服务器中到期,我想触发RPC回调“onFailure”。 我创建了一个自定义RPC AsyncCallback来处理来自服务器的“session expired”事件。 我重写了RemoteServiceServlet以在调用方法之前验证会话。所以基本上,抛出异常的声明方法不是自定义RemoteServiceServlet。它仍然转到客户端异步中的“onFailure”,但Throwable对象仍然是“StatusCodeException”类型,没有EXPIRED_SESSION_MSG消息。有什么想法吗?

自定义RemoteServiceServlet:

public class XRemoteServiceServlet extends RemoteServiceServlet {
    private final static String EXPIRED_SESSION_MSG = "ERROR: Application has expired session.";   
    @Override
    protected void onAfterRequestDeserialized(RPCRequest rpcRequest) {
        HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
        HttpSession session = httpServletRequest.getSession(false);
        if (session != null) {
            final String sessionIdFromRequestHeader = getSessionIdFromHeader();
            if (!isNullOrEmptyString(sessionIdFromRequestHeader)) {
                final String sessionId = session.getId();

                if (!sessionId.equals(sessionIdFromRequestHeader)) {
                    throw new RuntimeException(EXPIRED_SESSION_MSG);
                }
            }

自定义AsyncCallback:

public class XAsyncCallback<T> implements AsyncCallback<T> {
    private final static String EXPIRED_SESSION_MSG = "ERROR: Application has expired session.";

    @Override
    public void onFailure(Throwable caught) {
        final String message = caught.getMessage();

        if (!isNullOrEmptyString(message) && message.contains(EXPIRED_SESSION_MSG)) {
            com.google.gwt.user.client.Window.Location.reload();
        }

    }

    @Override
    public void onSuccess(T arg0) {

    }

    /**
     * Returns true if the string is null or equals to the empty string.
     * 
     * @param string the string to test
     * @return true if the string is empty
     */
    private static boolean isNullOrEmptyString(String string) {
        return string == null || "".equals(string);
    }
}

2 个答案:

答案 0 :(得分:2)

有关使用GWT RPC处理异常,请参阅here

“预期失败”是在服务方法的签名中声明的服务方法抛出的异常。这些异常会被序列化回客户端。

“意外的预期”是不属于服务方法签名的错误,或者是由SecurityExceptions,SerializationExceptions或RPC框架内的其他失败导致的错误。

您想要的是一个已检查的异常,因为您希望将其发送回客户端并对其执行某些操作。 RPC框架负责捕获它,序列化它并使用正确的异常调用onFailure方法。为此,您需要遵循以下准则:

  • 您需要在服务中指定 签名即异常可以 抛出。
  • 必须抛出异常 在服务实现方法中。

你正在做的是从一些甚至不应该抛出异常的方法中抛出一个未被发现的异常。所以RPC不知道到底发生了什么,并发回一条通用消息,说“嘿,发生了意想不到的事情,看看服务器日志”。

我知道您希望在每次通话时检查会话。最简单的方法是使用一种方法在servlet实现中检查它,并从所有服务方法中调用它。

否则,您可以通过查看类

来尝试覆盖GWT RPC框架
com.google.gwt.user.server.rpc.RPC

但这是相当高级的东西。

答案 1 :(得分:2)

如果您想要send exceptions via GWT-RPC,则必须使用checked exceptions。 RuntimeException是一个未经检查的异常,因此在这种情况下你不能使用它。

创建自己的异常,扩展Exception并实现Serializable。此外,您必须在方法声明中指明此方法可能会引发异常: