View Javadoc

1   package com.atlassian.plugins.rest.common.error.jersey;
2   
3   import java.util.List;
4   
5   import com.atlassian.plugins.rest.common.Status;
6   
7   import javax.ws.rs.WebApplicationException;
8   import javax.ws.rs.core.Context;
9   import javax.ws.rs.core.HttpHeaders;
10  import javax.ws.rs.core.MediaType;
11  import javax.ws.rs.core.Response;
12  import javax.ws.rs.ext.ExceptionMapper;
13  import javax.ws.rs.ext.Provider;
14  
15  /**
16   * A generic exception mapper that will map any {@link Throwable throwable}.  Handles the special case of
17   * {@link WebApplicationException}, which provides its own response.
18   *
19   * @since 1.0
20   */
21  @Provider
22  public class ThrowableExceptionMapper implements ExceptionMapper<Throwable>
23  {
24      @Context
25      private HttpHeaders headers;
26      
27      public Response toResponse(Throwable t)
28      {
29          Response wrappedResponse;
30          if (t instanceof WebApplicationException)
31          {
32              wrappedResponse = ((WebApplicationException)t).getResponse();
33          }
34          else
35          {
36              wrappedResponse = Status.error().message(t.getMessage()).response();
37          }
38          // REST-186:  apparently Jersey 1.8 doesn't always correctly apply content negotiation
39          // to responses generated by an ExceptionMapper, so we'll specify the type here.
40          MediaType responseType = MediaType.APPLICATION_XML_TYPE;
41          if (headers != null)
42          {
43              List<MediaType> types = headers.getAcceptableMediaTypes();
44              if (!types.isEmpty())
45              {
46                  responseType = types.get(0);
47              }
48          }
49          return Response.fromResponse(wrappedResponse).type(responseType).build();
50      }
51  }