简体   繁体   English

Google Cloud Endpoints自定义例外

[英]Google Cloud Endpoints Custom Exception

I have the following method that raise exception: 我有以下方法引发异常:

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

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

    ...
}

How to catch the error in android client AsyncTask? 如何捕获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;
}

The above didn't catch the UnauthorizedException. 上面没有捕获UnauthorizedException。

The exception happens on the App Engine server, not on the Android client. 例外情况发生在App Engine服务器上,而不是Android客户端上。 You must then find a way to send a message to the client to tell him what exception happened. 然后,您必须找到一种向客户端发送消息的方法,以告诉他发生了什么异常。

In Cloud Endpoints and other REST APIs, this is done using the HTTP result code and HTTP result message. 在Cloud Endpoints和其他REST API中,这是使用HTTP结果代码和HTTP结果消息完成的。

The Cloud Endpoints documentation explains how to match a custom exception to an HTTP result code . Cloud Endpoints文档说明了如何将自定义异常与HTTP结果代码进行匹配 However, in your case you could also use the provided com.google.api.server.spi.response.UnauthorizedException . 但是,在您的情况下,您还可以使用提供的com.google.api.server.spi.response.UnauthorizedException This will translate into an HTTP 401 code, which is a way for HTTP to say "unauthorized". 这将转换为HTTP 401代码,这是HTTP说“未授权”的一种方式。

I have never tried Cloud Endpoints on Android, but if you check the exception class, you will certainly see that there is a way to get the HTTP error code. 我从来没有在Android上尝试过Cloud Endpoints,但是如果你检查异常类,你肯定会发现有一种方法可以获取HTTP错误代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM