title: Handling and Mapping Runtime Exceptions in REST Resource to JAX-RS Response
body: <p>I have a RESTful web application that connects to a database and has the normal REST, business logic service and persistence layers. What is the JAX-RS standard approach to handling Runtime errors, like database connection is not available, in a RESTful layer? I believe the approach I have below, where I wrap any call to my service/persistence layers with a try/catch for the Throwable and throw my custom MyAppRuntimeException is a bit awkward.  Any suggestions?</p>
  
  <p><strong>RESTful Service:</strong></p>
  
  <pre><code>@Path("service")
  @Consumes({"application/json"})
  @Produces({"application/json"})
  public class MyResource {
    @GET
    @Path("/{id}")
    public Response getPage(@PathParam("id") long id){
      Object test=null;
      try {
           test = ...
        //call business logic service method here which makes a call to database and populates test instance
      } catch (Throwable e) {
        throw new MyAppRuntimeException("custom error message string");
      }
  
      if(test != null){
          return Response.ok(test).build();
      }else{
          return Response.status(Status.NOT_FOUND).build();
      }
  
    }
  }
  </code></pre>
  
  <p><strong>Custom Exception:</strong></p>
  
  <pre><code>public class MyAppRuntimeException extends RuntimeException {
    private static final long serialVersionUID = 1L;
  
  
    public MyAppRuntimeException(String message) {
      super(message);
    }
  
    public MyAppRuntimeException(String message, Throwable cause) {
      super(message, cause);
    }
  
  
  } 
  </code></pre>
  
  <p><strong>Exception JAX-RS Response Mapper:</strong></p>
  
  <pre><code>@Provider
  public class MyAppRuntimeExceptionMapper implements ExceptionMapper&lt;MyAppRuntimeException&gt; {
  
    private static final String ERROR_KEY = "DATA_ERROR";
  
    @Override
    public Response toResponse(MyAppRuntimeException exception) {
  
      ErrorMessage errorMessage = new ErrorMessage(ERROR_KEY, exception.getMessage(), null);
      return Response.status(Status.INTERNAL_SERVER_ERROR).entity(errorMessageDTO).build();
    }
  
  }
  </code></pre>