I have a rest service which will throw an exception and I want to know what will be the best way to handle this.
So I have a rest service which can throw a userdefined exception and I am catching that inside the catch block and throwing that exception again ! and using rest framework to catch that. Similarly for non-user defined exceptions. I thought this will be good as I have number of rest services and all userdefinedexception code handling will be at a same place.
I would like to know is this the proper way of handling exception in rest service ?
I am using jersey.
// rest service @POST public void doSomething() { try { // ... some piece of code that can throw user defined exception as well as runtime exception } catch(UserDefinedException e) { throws new UserDefinedException(e); } catch(Exception e) { throws new ServiceException(e); } // Now I have a @Provider to catch this thrown exception @Provider public class UserDefinedExceptionHandler implements ExceptionMapper { public Response toResponse(UserDefinedException exception) { ClientResponse clientResponse = new ClientResponse(); ResponseStatus status = new ResponseStatus(); clientResponse = handleUserDefinedException(exception, status, clientResponse); return Response.ok(clientResponse).build(); } // similarly for the ServiceException