5

I have implemented some custom exceptions like: NotFoundException, BadRequestException,

and for each of them I have implemented its own ExceptionMapper like NotFoundExceptionMapper, BadRequestExceptionMapper and also something like GenericExceptionMapper:

@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {


    @Override
    @Produces( {MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON} )
    public Response toResponse(Throwable ex) {
        ErrorResponseWrapper errorResponse = new ErrorResponseWrapper(ex.getMessage(), 500, "");
        return Response.status(Status.INTERNAL_SERVER_ERROR).entity(errorResponse).build();
    }
}

Firstly the problem here is that GenericExceptionMapper doesn't work as I expected it doesn't catch generic exceptions thrown by JAX-RS as I think each Exception to be caught by such Mapper must be early explicitly thrown from the method like getResource() throws SomeException {

Moreover the problem is that in RestEasy I need to register exception mappers in web.xm. See below:

 <!-- Custom exception handling provider -->
    <context-param>
        <param-name>resteasy.providers</param-name>
        <param-value>pl.salonea.jaxrs.exceptions.GenericExceptionMapper</param-value>
    </context-param>

Here is another problem as I can not register (or I don't know how to register) each custom ExceptionMapper I have defined. I can only register SINGLE custom ExceptionMapper. How to register all of them? i.e. NotFoundExceptionMapper, BadRequestExceptionMapper, etc.

So now each exception is mapped only by Generic Exception Mapper and that is the first problem.

Is this limitation of RESTEasy? in Jersey on some tutorial I haven't seen the need to register such ExceptionMappers but I also don't know whether there can be more than one exception Mapper.

Another solution (workaround) that came to my mind is to have single GenericExceptionMapper and in the method toResponse(Throwable ex) makes some checks like:

if(ex instanceof NotFoundException) { // send response type 1 
if(ex instanceof BadRequestException) { // send response type 2

Thx for help

Michał Ziobro
  • 10,759
  • 11
  • 88
  • 143
  • I think the best strategy is the "another solution". Distribute the different exceptions in different exception mappers bring more problems than solutions when some developer, not aware about how you organize this, would like to maintain this code. I know, this can sound "lazy", but sometimes is the best alternative, because this code will not be so long. – Dherik Aug 24 '16 at 17:44

0 Answers0