Saturday, 13 August 2016

java - Rest service throws exception : Best way to handle



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

Answer



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"
}
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...