Rest service throws exception : Best way to handle

15,693

Solution 1

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

Solution 2

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.

Share:
15,693
Anuj Kulkarni
Author by

Anuj Kulkarni

https://www.youtube.com/watch?v=H_nPM0HhKJg I am a Java, JavaEE, Groovy, Grails, Javascript, EmberJS, Python developer. Holds MS in Computer Science. Tags : Java, Java EE, Algorithms, Data Structures, Git, Linux, Android, MapReduce, Spring, Python,Groovy, Grails, Javascript, EmberJS. Why Stackoverflow sucks - 1 2 3 4 5 6 7 8 9 And on and on and on...

Updated on June 07, 2022

Comments

  • Anuj Kulkarni
    Anuj Kulkarni almost 2 years

    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