Jersey Exception mappers not working when jackson deserialization fails

后端 未结 5 2034
借酒劲吻你
借酒劲吻你 2020-12-29 06:57

I am using Jersey 2.10 with Jackson serialization/deserialization feature in my REST API.

My idea is to make my REST API to always return a standard JSON error resp

5条回答
  •  太阳男子
    2020-12-29 07:39

    I had the same problem, and the previous answer led me to the solution, but was not forking for me current Jersey (2.22). At first, I needed to use the org.glassfish.jersey.spi.ExtendedExceptionMapper like described in https://jersey.java.net/documentation/latest/representations.html.

    Furthermore, Jersey is checking for an exception mapper, which is as close as possible to the thrown exception (from org.glassfish.jersey.internal.ExceptionMapperFactory):

    for (final ExceptionMapperType mapperType : exceptionMapperTypes) {
            final int d = distance(type, mapperType.exceptionType);
            if (d >= 0 && d <= minDistance) {
                final ExceptionMapper candidate = mapperType.mapper.getService();
    
                if (isPreferredCandidate(exceptionInstance, candidate, d == minDistance)) {
                    mapper = candidate;
                    minDistance = d;
                    if (d == 0) {
                        // slight optimization: if the distance is 0, it is already the best case, so we can exit
                        return mapper;
                    }
                }
            }
        }
    

    Therefore I needed to map exactly the exception and not a more general exception.

    In the end, my provider looks as follows:

    @Provider
    public final class JsonParseExceptionExceptionHandler implements ExtendedExceptionMapper {
        @Override
        public Response toResponse(final JsonParseException exception) {
            exception.printStackTrace();
            return Response.status(Response.Status.BAD_REQUEST).entity("JSON nicht in korrektem Format.").build();
        }
    
        @Override
        public boolean isMappable(final JsonParseException arg0) {
            return true;
        }
    }
    

提交回复
热议问题