Tuesday, June 12, 2012

RESTEasy Tutorial Part 3 - Exception Handling


RESTEasy Tutorial Series

RESTEasy Tutorial Part-1: Basics

RESTEasy Tutorial Part-2: Spring Integration

RESTEasy Tutorial Part 3 - Exception Handling

Exception Handling is an obvious requirement while developing software application. If any error occured while processing user request we should show the user an error page with details like brief exception message, error code(optional), hints to correct the input and retry(optional) and actual root cause(optional). This is applicable to RESTful web services also.

But putting try-catch-finally blocks all around the code is not a good practice. We should design/code in such a way that if there is any unrecoverable error occured then the code should throw that exception and there should an exception handler to catch those exceptions and extract the error details and give a proper error response to the client with all the error details.

RESTEasy provides such ExceptionHandler mechanism which simplifies the ExceptionHandling process.

In this part I will show you how we can use RESTEasy's ExceptionHandlers to handle Exceptions.

Step#1: Create Application Specific Exceptions.
Step#2: Create ExceptionHandlers by implementing ExceptionMapper interface.

Step#3: Update UserResource.getUserXMLById() method to validate user input and throw respective exceptions.

Step#4: Test the UserResource.getUserXMLById() service method by issueing following requests.



Important things to note:
As Spring is creating the necessary objects we should let Spring know about @Provider classes to get them registered with RESTEasy. We can do this in two ways.

a)Annotate Provider classes with @Component

b)Using component-scan's include-filter.

<context:component-scan base-package="com.sivalabs.springdemo">
         <context:include-filter expression="javax.ws.rs.ext.Provider" type="annotation"/>
</context:component-scan>

2 comments:

  1. Hi Siva,
    Nice article. I need to contact you regarding a suggestion. Please drop me a mail back here http://techsamosa.com/blogs/about-us/

    ReplyDelete
  2. Hi Siva.
    Its a nice article.
    I am throw ApplicationException from a normal java class. Then the ApplicationExceptionHandler is not handling the exception. The ApplicationExceptionHandler handling the exceptions only when they are thrown from jersey resources(Eg : UserResource).
    How can we make the ApplicaionExceptionHandler to handle exceptions which are thrown by normal java classes.
    Thanks and Regards,
    Siva.

    ReplyDelete