Saturday, March 4, 2017

REST Endpoint returning 404 without Exceptions

At some point in your REST endpoint design, you will need to return a non 200 response. Now, most implementations show how to implement this using exceptions. While this may seem like a nice approach (from a programming language point of view), exceptions can add overhead to the running JVM. This translates to ineffective use of resources of the JVM for supporting non 200 responses.

Here is a gist where you don't use exceptions to return non 200 responses:

A few things to note from this snippet:
  1. This is a Spring Boot implementation (Boot makes things so much simple)
  2. The HttpServletResponse is injected by Boot (Spring MVC), no need of additional setup.
  3. Notice that the body return is null already, so the non 200 response makes more sense.
Please note that this is an implementation specific construct to support non 200 responses. Jersey and others also provide a non exceptional way to handle this scenario. Semantics of what the endpoint does (nouns non verbs, uniform contracts, interfaces, etc) are not part of the discussion. This is strictly an implementation description meant to support the abstraction defined by the given REST endpoint.