Search code examples
javaspringtry-catchaop

How to get rid of try/catch method inside every method


I have application with many rest services, most of them follows this pattern:

class RestService{

   public Response execute1() {
      try{
         // doLogicThere...

         return response;
       } catch () {
         // handle exception and build Response object..

         return response;
       }
   }

   public Response execute2() {
       try{
          // doLogicThere...

          return response;
       } catch() {
          // handle exception and build Response object..

          return response;
       }
   }
}

catch clause is the same for all methods so I want to have pattern like this below but with try/catch called from somewhere else. I want to do kind of wrapping these methods.

class RestService{

    public Response execute1() {
        // doLogicThere...

        return response;
    }

    public Response execute2() {
       // doLogicThere...

       return response;
    }
}

Solution

  • JAX-WS includes a mechanism for creating the proper response for each type of exception that your REST methods might produce.

    For each exception type, create a class that implements ExceptionMapper<E> where E is the type of exception. You create your response in the toResponse method. You need to annotate your exception mapper with @Provider, in order to register it with the JAX-RS runtime.

    @Provider
    public class UserNotFoundMapper implements ExceptionMapper<UserNotFoundException> {
        @Override
        public Response toResponse(UserNotFoundException e) {
            return Response.status(404).entity(e.getMessage()).type("text/plain").build();
        }
    }