1
votes

I have a JAX-RS based web application. The application includes 2 types of APIs:

  1. typical rest(json) enpoints
  2. endpoint, which duplicates rest, but receives requests in XML format.

Both API produces different format response.

  1. json
  2. XML

I currently have single ExceptionMapper, to catch exceptions like:EJBAccessException, NotAllowedException...

Which can be produced by both API types.

My question: which is the best way to separate exception handling?
(reaction to same exception for rest api should generate JSON response, for XML - xml response)

1
Why do you have to duplicate resources just to support different content types? - ernest_k
By requirements. - PashaDoro
you shouldn't have to split the responses if the messages are identical, you can pack them in the same object on output. eg ErrorMessageForBothJSONXML and have a field which is used to serialize out. Generally, I like to have two exceptions which are thrown in this case, and inherit from the single exception, which is caught by the ExceptionMapper - Paul Bastide
Thanks for response. My case have a lot of legacy, Paul, your solution is not easy to integrate. But I have found solution by my self. And here you can see something similar what I already have done - > stackoverflow.com/questions/36375502/… - PashaDoro

1 Answers

0
votes
@Context private ResourceInfo resourceInfo;

@Override
public Response toResponse(Throwable throwable) {
    if(resourceInfo.getResourceClass().isAnnotationPresent(RestExceptionMapper.class)) {
        return RestExceptionHandler.handle(throwable, servletRequest);
    } else if (resourceInfo.getResourceClass().isAnnotationPresent(SoapExceptionMapper.class)) {
        SoapExceptionHandler.handle(throwable, servletRequest);
    }
    return Response.status(500).entity("ERROR").build();
}

This is a template of my new exception mapper. Linkage to resource using annotation.