The same ExceptionMapper for different exceptions

My application provides a RESTful interface to perform some actions. I use ExceptionMapper to detect exceptions like NoResultException or EntityNotFoundException , and then return a 404 status code or exceptions like NumberFormatException or ConstraintViolationException and return a 400 status code ... etc.

My problem is that ExceptionMapper only allows me to select one kind of exception each time; therefore, I cannot use the same class for all error 400 and another form for all error 404.

Is there a way to create an ExceptionMapper that displays two different kinds of exceptions?

My other option is to change my functions to return a response instead of a string (marked as @Produces("application/json")); and then set the status code every time, but I think this is the worst ...

+6
source share
1 answer

You can write one ExceptionMapper against a superclass of exceptions (i.e. java.lang.Exception ), and then provide different types of behavior based on a specific class of exceptions, for example:

 public class MyExceptionMapper implements ExceptionMapper<Exception> { @Override public Response toResponse(Exception exception) { if (exception instanceof EntityNotFoundException) { ... } else (exception instanceof NumberFormatException) { ... } else { // The catch-all handler... } } } 

But, in my opinion, this is not as clean as writing separate cartographers for each type of exception. Firstly, this cartographer will catch all Exceptions, and for another, this class can increase to cumbersome measurements over time. Perhaps this is a code style issue.

+3
source

Source: https://habr.com/ru/post/976785/


All Articles