java - Google Cloud Endpoints 自定义异常

标签 java android exception google-cloud-endpoints

我有以下引发异常的方法:

@ApiMethod(name = "login")
public Profile getLogin(User user) throws UnauthorizedException {

    if (user == null){
        throw new UnauthorizedException("missing user");
    }

    ...
}

如何在android客户端AsyncTask中捕获错误?

protected Profile doInBackground(Void... unused) {

    Profile profile = null;
    try {
        profile = service.login().execute();

    } catch (Exception e) {
        Log.d("exception", e.getMessage(), e);
    }

    return profile;
}

上面没有捕捉到 UnauthorizedException。

最佳答案

异常发生在 App Engine 服务器上,而不是 Android 客户端上。然后,您必须想办法向客户端发送消息,告诉他发生了什么异常。

在 Cloud Endpoints 和其他 REST API 中,这是使用 HTTP 结果代码和 HTTP 结果消息完成的。

Cloud Endpoints 文档解释了 how to match a custom exception to an HTTP result code .但是,在您的情况下,您还可以使用提供的 com.google.api.server.spi.response.UnauthorizedException。这将转换为 HTTP 401 代码,这是 HTTP 表示“未经授权”的一种方式。

我从未在 Android 上尝试过 Cloud Endpoints,但如果你检查异常类,你肯定会看到有一种方法可以获取 HTTP 错误代码。

关于java - Google Cloud Endpoints 自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20876028/

相关文章:

java - 如何向 fragment 选项卡添加动态 UI?

c++ - 如果赋值过程中发生异常,指针的值会改变吗?

spring - Spring 运行时异常列表

java - 循环和封装的使用

java - JSP 和 EL 与 JSF 1.x actionListener 冲突

java - 处理空列表 - 使用 ListFragment 或 Fragment+ListView 更好?

android - 在两个 View 之间沿着手指画线(ImageViews)

android - 图像 GridView 内部 fragment

asp.net - elmah 也处理捕获的异常吗

Java 客户端调用 Windows 集成身份验证 Web 服务