Google Cloud Endpoints Tips #2 : Throw the Right Exception Classes

Romin Irani
Romin Irani’s Blog
2 min readMay 29, 2014

December 2017: Please note that this post has not been updated for a while and there could be differences in terms of commands, screenshots and problems in running the code.

One of the hallmarks of a well-written API is to understand what it throws back to the clients when there is an exception.

For e.g. a REST API should make use of the correct HTTP Status Codes in its response. Some of the well-known status codes are 200 (OK) , 404 (Not Found), 500 (Internal Server Error) and so on. It is very important that you implement your Endpoint classes to throw back the correct status codes.

Cloud Endpoints does provide a mechanism for you to throw back Exception classes that will in return use the correct HTTP Status code in the response sent back to the client. As per the documentation, there are several exception classes made available in the com.google.api.server.spi.response package. Some of these exception classes are:

  • NotFoundException (HTTP 404)
  • UnauthorizedException (HTTP 401)

and so on. The usage is simple too. Here is a snippet for throwing a not found exception:

String message ="No entity exists with ID: "+ entityId;throw new NotFoundException(message);

The above would be the correct way to throw an exception. It is easy to make the mistake of throwing some other Java Exception (Persistence Layer), etc. This will result in a crazy response for the client with a trace, etc. So always catch the exceptions being thrown from the layers that Cloud Endpoints interacts with and then instantiate the correct exception.

Note that you can also create your own custom Exception classes that map to some other HTTP Codes. But do look out in the documentation for the status codes that you should not be overriding with your custom exception classes.

One of the areas where you will immediately notice the need for the correct exception classes is the default code that is generated for the endpoints from your Entity class. Look at the get and insert methods that it generates and you will find that it throws Entity Exceptions from the Persistence Layer. This is typically not a good idea and it is best to envelope this with the Exception classes that correctly map to the HTTP Codes.

Developers who are writing Client applications against your API and API tools will thank you.

List of Cloud Endpoints Tips

  1. Check Endpoint Deployment Status
  2. Throw the Right Exception Classes
  3. Understand Injected Types
  4. Understand @API and @APIMethod Annotation
  5. Using Cursor and Limit parameters
  6. The @APIResourceProperty Annotation

--

--

Romin Irani
Romin Irani’s Blog

My passion is to help developers succeed. ¯\_(ツ)_/¯