Java – Google Cloud Endpoints custom exceptions

Google Cloud Endpoints custom exceptions… here is a solution to the problem.

Google Cloud Endpoints custom exceptions

I have the following method to throw an exception:

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

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

...
}

How to catch errors 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;
}

UnauthorizedException is not caught above.

Solution

The exception occurs on the App Engine server, not the Android client. Then, you have to find a way to send a message to the client telling him what was wrong.

In Cloud Endpoints and other REST APIs, this is done using HTTP result codes and HTTP result messages.

The Cloud Endpoints documentation explains how to match a custom exception to an HTTP result code.However, in your case, you can also use the provided com.google.api.server.spi.response.UnauthorizedException. This translates to HTTP 401 code, which is a way for HTTP to mean “unauthorized.”

I’ve never tried Cloud Endpoints on Android, but if you check the exception class, you’ll definitely see that there’s a way to get the HTTP error code.

Related Problems and Solutions