Jersey/Jackson Exception problem with ExceptionMapper

前端 未结 5 1248
野趣味
野趣味 2021-02-04 05:07

I\'m using Jersey to provide a java REST service to the outside world. I offer some functions that take JSON and I use the Jackson framework in combination with jersey to conver

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-04 06:00

    I ran into a similar issue a while back while using Jackson and Apache CXF. The exception mappers weren't called if the exception didn't happen in my JAX-RS method and instead happened in the JacksonJsonProvider. The solution in my case was to extend JacksonJsonProvider, catch the specific Jackson json exceptions, and rethrow them as WebApplicationException.

    Here's my overriden readFrom method for my extended JacksonJsonProvider:

        @Override
        public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType,
                MultivaluedMap httpHeaders, InputStream entityStream) throws IOException {
            try {
                return super.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream);
            } catch (JsonParseException jpe) {
                throw new WebApplicationException(jpe, Response.status(Status.BAD_REQUEST)
                        .entity(new ErrorEntity("Malformed json passed to server: \n" + jpe.getMessage())).build());
            } catch (JsonMappingException jme) {
                throw new WebApplicationException(jme, Response
                        .status(Status.BAD_REQUEST)
                        .entity(new ErrorEntity("Malformed json passed to server, incorrect data type used: \n"
                                + jme.getMessage())).build());
            }
        }
    
        

    提交回复
    热议问题