Restful web services: Handling exception with WebApplicationException

Most of us use the below approach in our Rest services for handling the error response.


@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/contacts")
public Response getContactsById(@QueryParam("userId") String userId) {
        try {
            Contact contact = new ContactService().getContactsById(userId);
         return Response.ok().entity(contact).type(MediaType.APPLICATION_JSON).build();
        } catch (Exception ex) {
            LOGGER.error("Exception happened while getting contact data", ex);
            Throwable rootCause = Throwables.getRootCause(ex);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).
                    entity(rootCause.getMessage()).type(MediaType.APPLICATION_JSON).build();
        }
    }

So in the above code, if there is any issue/exception, then we catch that exception and get the root cause of it and create a new Response object with that and send it as JSON.

We can use the WebApplicationException instead of catching that error and creating a response object.

Below is the example for handling the above with WebApplicationException.


public class ContactNotFoundException extends WebApplicationException {

    public ContactNotFoundException(String message) {
        super(Response.status(Status.NOT_FOUND).entity(message)
                .type(MediaType.APPLICATION_JSON).build());
    }
}


@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/contacts")
public Response getContactsById(@QueryParam("userId") String userId) throws ContactNotFoundException {
        try {
            Contact contact = new ContactService().getContactsById(userId);
            return Response.ok().entity(contact).type(MediaType.APPLICATION_JSON).build();
        } catch (Exception ex) {
            LOGGER.error("Exception happened while getting contact data", ex);
            throw new ContactNotFoundException(ex.getMessage());
        }
    }

So in the above example, we create a custom exception ContactNotFoundException which extends the WebApplicationException. Inside the constructor, we create a response with proper status code and error message.

So in our Resource class, we use handle the exception and instead of creating a Response object, just throw the ContactNotFoundException with the message in it. Once we do this, then Rest of things are handled by Jersey framework itself.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s