4
votes

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
2

2 Answers

5
votes

Just raising error 500 at the server don't give much details on the error, one way to gracefully handle errors, is to wrap the response data in a structure with status and data, if the status is error, show the correct message.

something like this in json format :

{
    "status": "error",
    "data": {
        "message": "detailed error message"
    }
}
1
votes

Handling exceptions in a REST service is not much different from handling exceptions in any other piece of code.

The only "convention" is to throw back an HTTP 400 if the exception is triggered by the client sending incorrect data and a 500 when your service is failing unexpectedly.