Get all updates of Java4s
Follow Us: Email Newsletter

Exception Handling in RESTful Web Services (JAX-RS) with Jersey

Exception handling in RESTful (JAX-RS) web services is a very important concept, in this article I am going to explain it step by step with an example. FYI. check this article for Creating Simple Maven RESTful Web Service Project in Eclipse. I am directly going to start with directory structure of the current example.

Directory structure

As we are dealing with exception handling, I am going to create a service which will throw an exception :-)

pom.xml

web.xml

RESTResource.java

RESTService.java

CallDB.java

MyData.java

Explanation

So we are good to run the application now,  if you observe I have just created 4 java classes till now..

  • RESTResource.java
  • RESTService.java
  • CallDB.java
  • MyData.java

The application will start by hitting the following URL [ I am using 2017 as my server port, this might be different for your server]

http://localhost:2017/RESTExceptionHandlingExample/customers/checkProfile/100

  • If you hit the above URL, the flow will come to RESTResource.java, in that at line number 17, I am calling checkCustomerStatus( – ) function of RESTService class, by passing the id
  • Consider, CallDB is a class which handle all database related stuff, so in RESTService.java > line number 11, I am calling getStatus( – ) of CallDB
  • In CallDB.java > consider we had a database call at line number 7,  after that creating MyData class object and setting all the data that I retrieved from the database and returning it at line number 13, if you observe line number 11, I have commented the setter method, means I am not setting status, so by default it contains NULL value ( if we call its getter method, it will return NULL)
  • Now the flow will come to RESTService.java > at line number 11, I am calling getStatus(), as this gives null value [as we have not set anything in CallDB > line 11], on that null I am calling .trim() again, which will give NullPointerException :-)

Hmm.. so successfully we are able to create a service, which will throw a NullPointerException :-) If you hit the URL, you will see..


Its the Tomcat default error page, showing the exception as NullPointerException but I don’t think its the right way of displaying the errors to the consumers! lets try to display the error with some custom error message, in order to do that I am going to create a custom (user defined) run time exception, lets say my custom exception class name is CustomerDataNotFoundException.

CustomerDataNotFoundException.java

Here I have just created an exception class with constructor which takes String as an argument, now let me change RESTService.java as..

RESTService.java

I am checking the status with if condition. If status is NULL, throwing out the custom exception by passing some meaningful message. Lets run the application and see..


Its throwing our exception with the message we have sent, not bad ;) but still this is not the right way of showing the errors.

What happens behind the scenes

Actually we are throwing CustomerDataNotFoundException if the status is NULL, if you observe, we are not handling that exception in RESTService, instead simply throwing with our message. So the exception keeps bubbling up and will come to RESTResource (here also we are not handling ) and so from there to JAX-RS and finally will reach Tomcat server container, and server will show its default error page, that’s what we are seeing in the above image.

So in order to stop exception bubbling up to the tomcat server container, we need to create an exception mapper.

CustomerDataNotFoundExceptionMapper.java

ErrorProps.java

Explanation

  • Created an exception mapper CustomerDataNotFoundExceptionMapper for CustomerDataNotFoundException 
  • All exception mappers should implement ExceptionMapper interface of type generic, for now I am going to use this exception mapper only for our exception, so I have implemented ExceptionMapper of type CustomerDataNotFoundException [check at line number 9]
  • We need to override the toResponse method of ExceptionMapper interface, which takes exception as an argument, in this case CustomerDataNotFoundException
  • I want to display my exception details as an XML, so created a simple java model ErrorProps.java and annotated with @XmlRootElement
  • Now come back to mapper class toResponse method, there I am returning Response object

    Response.status( – ) :- setting the current status
    .entity( – ) :- passing ErrorProps class object by setting required values, here I am setting status as 404, and our custom exception message

  • Finally annotate our mapper class with @Provider annotation, so that JAX-RS will register this mapper to intercept the response when particular exception was thrown

Go ahead and run the application and see…

 

We did it :-)

But this is only for NullPointerException, but how about the other exceptions ? for that we need to modify the mapper. Let me do it by creating new mapper class.

GenericExceptionMapper.java

What are the changes ?

Implement ExceptionMapper of type Throwable, instead of our own exception. If you check the above class, at line number 13, I am checking whether the Throwable is the instance of CustomerDataNotFoundException, if its true, I will build my Response accordingly, like this you can handle any number of exceptions in a single class, you can download and play with it.

That’s it friends, hope you enjoy the article ;)

You Might Also Like

  ♦ About Author ♦

Java4s_Author
sivateja@java4s.com
Full Stack( Java/J2EE & UI/UX ) Developer and founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog. Sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

2 Responses to “Exception Handling in RESTful Web Services (JAX-RS) with Jersey”
  1. mangesh says:

    Very easy to understand for all concepts. Please provide Design Pattern tutorial

  2. Vamshi Krishna says:

    I have seen lot blogs and Information on other sites But in this Blog Information is very useful

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
What would you like to learn today?
Browse these popular technologies
Hibernate spring struts Servlets ajax Log4j jQuery Json Core Java Web Services AngularJs
Most Recent Tutorials
Hibernate_Logo Hibernate Recent Posts Spring_Logo Spring Recent Posts Struts_Logo Struts Recent Posts
Useful LinksCurrent & UpComing Tutorials
Upcoming
  Web Services [ SOAP ], JSP
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2017 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.