0

My application has many different API REST build with Jersey 2.34. All the url starts with "/api/" following by the service's name, for example: /api/foo, /api/bar, etc.

In my web.xml, the servlet is declared:

<servlet>
       <servlet-name>jersey-serlvet</servlet-name>
       <servlet-class>
           org.glassfish.jersey.servlet.ServletContainer
       </servlet-class>
       <init-param>
           <param-name>jersey.config.server.provider.packages</param-name>
           <param-value>com.restapi</param-value>
       </init-param>
       <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
       <servlet-name>jersey-serlvet</servlet-name>
       <url-pattern>/api/*</url-pattern>
   </servlet-mapping>

I have a CustomExceptionMapper to respond with a custom message:

@Priority(1)
@Provider
public class CustomJsonMapperException implements ExceptionMapper<JsonMappingException> {

    @Override
    public Response toResponse(JsonMappingException bex) {
        return Response.status(400).entity(MY_CUSTOM_MESSAGE).build();
    }

}

How can I apply my CustomJsonMapperException only for one api service, for exemple only for "/api/foo" and not all other "/api/*"?

Janny
  • 33
  • 6

1 Answers1

0

With some explications from this thread how to map JSON parsing related errors to json response in jersey , I managed to make it as following:

  • Add a HttpServletRequest object to retrieve the api path called
  • Filter the returned response based on the the api path called: if it is a API which need a custom message -> return custom message, else return the default message managed by Jersey & Jackson (JsonMappingExceptionMapper).
@Priority(1)
@Provider
public class CustomJsonMappingException implements ExceptionMapper<JsonMappingException> {
    @Context
    HttpServletRequest request;

    @Override
    public Response toResponse(JsonMappingException ex) {
        //return the custom message only for service "api/foo"
        if (request.getPathInfo().startsWith("/foo")) {
            return Response.status(400).entity(MY_CUSTOM_MESSAGE).build();
        } else {
            //all others api services
            return new JsonMappingExceptionMapper().toResponse(ex);
        }
    }
}

It is solved but any correction and/or improvement are welcome!

Janny
  • 33
  • 6