View Javadoc

1   package com.atlassian.plugins.rest.common.error.jersey;
2   
3   import javax.ws.rs.WebApplicationException;
4   import javax.ws.rs.core.Context;
5   import javax.ws.rs.core.Request;
6   import javax.ws.rs.core.Response;
7   import javax.ws.rs.ext.ExceptionMapper;
8   import javax.ws.rs.ext.Provider;
9   
10  import org.slf4j.Logger;
11  import org.slf4j.LoggerFactory;
12  
13  /**
14   * A generic exception mapper that will map any {@link Throwable throwable}.  Handles the special case of
15   * {@link WebApplicationException}, which provides its own response.
16   *
17   * @since 1.0
18   */
19  @Provider
20  public class ThrowableExceptionMapper implements ExceptionMapper<Throwable> {
21      private static final Logger log = LoggerFactory.getLogger(ThrowableExceptionMapper.class);
22  
23      @Context
24      Request request;
25  
26      public Response toResponse(Throwable t) {
27          if (t instanceof WebApplicationException) {
28              // Internal Server Error: a bug or other error -> log it with a stack trace just in case it wasn't logged already
29              // Note that other 5xx codes are specific well-known codes that do not indicate a potential bug.
30              // For more details see: https://bitbucket.org/atlassian/atlassian-rest/pull-request/12#comment-1088837
31  
32              final WebApplicationException webEx = (WebApplicationException) t;
33              if (webEx.getResponse().getStatus() == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
34                  log.error("Server Error in REST: " + webEx.getResponse().getStatus() + ": " + webEx.getResponse(), t);
35              } else {
36                  log.debug("REST response: {}: {}", webEx.getResponse().getStatus(), webEx.getResponse());
37              }
38              return webEx.getResponse();
39          } else {
40              log.error("Uncaught exception thrown by REST service: " + t.getMessage(), t);
41              return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
42                      .entity(new UncaughtExceptionEntity(t))
43                      .type(UncaughtExceptionEntity.variantFor(request))
44                      .build();
45          }
46      }
47  }