Now what if the Client sends a tweetID for which there is no tweet available in database. For example:

/tweet/25
// no content(as Response)

It’s not something that the Client of the Rest Service wants to see. In such cases, we can create our own custom exceptions. This way, if someone tries to access a tweet that’s not available in server, we simply throw an exception rather return empty content.

Now if we access /tweet/25 but the particular tweet ID isn’t available, we get the Tomcat Error Page because we are throwing INFONotFoundException in our business class but not catching it. It bubbles up in JAX_RS, which also doesn’t know what to do with this exception, so it goes up to servlet container which has a default behavior to show standard error page in case something wrong happened in server side code.

We don’t want an HTML error Page for the exception as the response of Rest API End Point, though. We want a JSON payload as the response so it is useful to the client who is consuming the REST API, so they can parse it accordingly. For this, we would like JAX-RS framework to catch it and return a JSON payload before it goes up to servlet container.

Now, when JAX-RS sees any INFONotFoundException in the application, it searches all ExceptionMapper‘s annotated with @Provider in application and tries to find a mapper which could map the INFONotFoundException to a ErrorResponse. Once it finds a suitable ExceptionMapper, it passes the thrown Exception to the method argument of toResponse(Exception ex) in ExceptionMapper and builds a JSON payload by calling toResponse(Exception e) method of ExceptionMapper.

Now, the client does not see an HTML error page anymore and JAX-RS gives a nice JSON payload which can help the client with troubleshooting.

Note:

1. We can include ExceptionMapper in our REST API in order to address specific Exceptions to be more helpful to the client.

2. It’s always good practice to create a generic ExceptionMapper in case the developer doesn’t want to create multiple mappers for each exception thrown in application. This way, no matter what goes wrong in our server side REST API (e.g NullPointerException, DataNotFoundException, etc.), JAX-RS always tries to map it with GenericExceptionMapper and we never see the HTML Error page but instead a JSON payload which can be helpful for the service client.