04.Exception Handling - JohnyzHub/jax-rs GitHub Wiki

Exceptions can be handled in restful web services, as described below

  1. By throwing the subclass of WebApplicationException
  2. Create an exception by extending WebApplicationException, and throw it.
  3. Using ExceptionMapper

ExceptionMapper:

Below are the steps to create an exception mapper for any existing exception.

  1. Create a mapper class for the exception(eg:ArithmeticException) by implementing ExceptionMapper

  2. Override the toResponse method of ExceptionMapper

  3. Register this new exception mapper class to the application configuration

    When the application results in the ArithmeticException anytime during the execution, the response defined in the inherited exception mapper class will be returned to the client.

Example erroneous response resulted by ArithmenticExceptionMapper

    Status: 400 Bad Request   
       
           {
              "code": "ERR-????",
              "type": "General Error",
              "message": "/ by zero"
           }

Notice, There is already a predefined BadRequestException exist in the JAX-RS specification.