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
- Check Endpoint Deployment Status
- Throw the Right Exception Classes
- Understand Injected Types
- Understand @API and @APIMethod Annotation
- Using Cursor and Limit parameters
- The @APIResourceProperty Annotation