title: How should I log uncaught exceptions in my RESTful JAX-RS web service?
body: <p>I have a RESTful web service running under Glassfish 3.1.2 using Jersey and Jackson:</p>
  
  <pre><code>@Stateless
  @LocalBean
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  @Path("users")
  public class UserRestService {
      private static final Logger log = ...;
  
      @GET
      @Path("{userId:[0-9]+}")
      public User getUser(@PathParam("userId") Long userId) {
          User user;
  
          user = loadUserByIdAndThrowApplicableWebApplicationExceptionIfNotFound(userId);
  
          return user;
      }
  }
  </code></pre>
  
  <p>For expected exceptions, I throw the appropriate <a href="http://docs.oracle.com/javaee/6/api/javax/ws/rs/WebApplicationException.html" rel="noreferrer"><code>WebApplicationException</code></a>, and I'm happy with the HTTP 500 status that is returned if an unexpected exception occurs.</p>
  
  <p>I would now like to add logging for these unexpected exceptions, but despite searching, cannot find out how I <em>should</em> be going about this.</p>
  
  <h2>Fruitless Attempt</h2>
  
  <p>I have tried using a <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.UncaughtExceptionHandler.html" rel="noreferrer"><code>Thread.UncaughtExceptionHandler</code></a> and can confirm that it is applied inside the method body, but its <code>uncaughtException</code> method is never called, as something else is handling the uncaught exceptions before they reach my handler.</p>
  
  <h2>Other Ideas: #1</h2>
  
  <p>Another option I've seen some people use is an <a href="http://docs.oracle.com/javaee/6/api/javax/ws/rs/ext/ExceptionMapper.html" rel="noreferrer"><code>ExceptionMapper</code></a>, which catches all exceptions and then filters out WebApplicationExceptions:</p>
  
  <pre><code>@Provider
  public class ExampleExceptionMapper implements ExceptionMapper&lt;Throwable&gt; {
      private static final Logger log = ...;
  
      public Response toResponse(Throwable t) {
          if (t instanceof WebApplicationException) {
              return ((WebApplicationException)t).getResponse();
          } else {
              log.error("Uncaught exception thrown by REST service", t);
  
              return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                     // Add an entity, etc.
                     .build();
          }
      }
  }
  </code></pre>
  
  <p>While this approach may work, it feels to me like misuse of what ExceptionMappers are supposed to be used for, that is, mapping certain exceptions to certain responses.</p>
  
  <h2>Other Ideas: #2</h2>
  
  <p>Most sample JAX-RS code returns the <a href="http://docs.oracle.com/javaee/6/api/javax/ws/rs/core/Response.html" rel="noreferrer"><code>Response</code></a> object directly. Following this approach, I could change my code to something like:</p>
  
  <pre><code>public Response getUser(@PathParam("userId") Long userId) {
      try {
          User user;
  
          user = loadUserByIdAndThrowApplicableWebApplicationExceptionIfNotFound(userId);
  
          return Response.ok().entity(user).build();
      } catch (Throwable t) {
          return processException(t);
      }
  }
  
  private Response processException(Throwable t) {
      if (t instanceof WebApplicationException) {
          return ((WebApplicationException)t).getResponse();
      } else {
          log.error("Uncaught exception thrown by REST service", t);
  
          return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                 // Add an entity, etc.
                 .build();
      }
  }
  </code></pre>
  
  <p>However, I'm leery of going this route, as my actual project is not as simple as this example, and I would have to implement this same pattern over and over again, not to mention having to manually build up the Responses.</p>
  
  <h2>What should I do?</h2>
  
  <p>Are there better methods for adding logging for uncaught exceptions?
  Is there a "right" way of implementing this?</p>