Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same ExceptionMapper for different exceptions

Tags:

java

rest

jersey

My application provides a RESTful interface to perform some actions. I'm using ExceptionMapper to catch exceptions like NoResultException or EntityNotFoundException and then return an status code of 404, or exceptions like NumberFormatException or ConstraintViolationException and return an status code of 400... etc.

My problem is that the ExceptionMapper only allows me to choose one kind of Exception each time; so I can't use the same class for all the error 400 and other form all the error 404.

Is there any way to create an ExceptionMapper that maps two different kind of exceptions?

My other option is change my functions to return a Response instead of an String (tagged as @Produces("application/json")); and then set the status code each time; but I think it's worst...

like image 590
Pedro Náñez Avatar asked Oct 15 '14 15:10

Pedro Náñez


1 Answers

You could write a single ExceptionMapper against an exception superclass (i.e. java.lang.Exception) and then provide different behaviors based on the specific exception class, 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 isn't as clean as writing separate mappers for each type of exception. For one thing, this mapper will catch all Exceptions, and for another this class could grow to unwieldy dimensions over time. Perhaps it's a matter of code style.

like image 118
sherb Avatar answered Sep 21 '22 07:09

sherb