简体   繁体   中英

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?

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.

The exception happens on the App Engine server, not on the Android client. 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.

The Cloud Endpoints documentation explains how to match a custom exception to an HTTP result code . However, in your case you could also use the provided com.google.api.server.spi.response.UnauthorizedException . This will translate into an HTTP 401 code, which is a way for HTTP to say "unauthorized".

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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