javaspringapirestjersey

CustomExceptionMapper only for a specific API Rest with Jersey


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/*"?


Solution

  • 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:

    @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!