04.Exception Handling - JohnyzHub/jax-rs GitHub Wiki
Exceptions can be handled in restful web services, as described below
- By throwing the subclass of WebApplicationException
- Create an exception by extending WebApplicationException, and throw it.
- Using ExceptionMapper
ExceptionMapper:
Below are the steps to create an exception mapper for any existing exception.
-
Create a mapper class for the exception(eg:ArithmeticException) by implementing ExceptionMapper
-
Override the toResponse method of ExceptionMapper
-
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.