About Siva Reddy

Katamreddy Siva Prasad is a Senior Software Engineer working in E-Commerce domain. His areas of interest include Object Oriented Design, SOLID Design principles, RESTful WebServices and OpenSource softwares including Spring, MyBatis and Jenkins.

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.

 **
  * ResourceNotFoundException.java
  *
 package com.sivalabs.resteasydemo;
 
 public class ResourceNotFoundException extends RuntimeException
 {
  private static final long serialVersionUID = 1L;
  public ResourceNotFoundException(String msg)
  {
   super(msg);
  }
 }
 
 **
  * ApplicationException.java
  *
 package com.sivalabs.resteasydemo;
 
 import java.io.PrintWriter;
 import java.io.StringWriter;
 
 public class ApplicationException extends RuntimeException
 {
  private static final long serialVersionUID = 1L;
 
  public ApplicationException()
  {
   super();
  }
  public ApplicationException(String message, Throwable cause)
  {
   super(message, cause);
  }
  public ApplicationException(Throwable cause)
  {
   super(cause);
  }
  public ApplicationException(String msg)
  {
   super(msg);
  }
  public String getInternalErrorMessage()
  {
   Throwable cause = this.getCause();
   if(cause != null)
   {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    cause.printStackTrace(pw);
    return sw.toString();
   }
   return null;
  }
 }

Step#2: Create ExceptionHandlers by implementing ExceptionMapper interface.

 **
  * ResourceNotFoundExceptionHandler.java
  *
 package com.sivalabs.resteasydemo;
 
 import javax.ws.rs.core.Response;
 import javax.ws.rs.ext.ExceptionMapper;
 import javax.ws.rs.ext.Provider;
 
 import org.springframework.stereotype.Component;
 
 @Provider
 @Component
 public class ResourceNotFoundExceptionHandler implements ExceptionMapper<ResourceNotFoundException>
 {
 
  @Override
  public Response toResponse(ResourceNotFoundException ex)
 
   For simplicity I am preparing error xml by hand.
   Ideally we should create an ErrorResponse class to hold the error info.
   String msg = ex.getMessage();
   StringBuilder response = new StringBuilder('<response>');
   response.append('<status>failed<status>');
   response.append('<message>'+msg+'<message>');
   response.append('<response>');
 
   return Response.serverError().entity(response.toString()).build();
  }
 
 }
 
 **
  * ApplicationExceptionHandler.java
  *
 package com.sivalabs.resteasydemo;
 
 import javax.ws.rs.core.Response;
 import javax.ws.rs.ext.ExceptionMapper;
 import javax.ws.rs.ext.Provider;
 
 import org.springframework.stereotype.Component;
 
 @Provider
 @Component
 public class ApplicationExceptionHandler implements ExceptionMapper<ApplicationException>
 {
  @Override
  public Response toResponse(ApplicationException ex)
  {
   For simplicity I am preparing error xml by hand.
   Ideally we should create an ErrorResponse class to hold the error info.
   String msg = ex.getMessage();
   String internalError = ex.getInternalErrorMessage();
   StringBuilder response = new StringBuilder('<response>');
   response.append('<status>failed<status>');
   response.append('<message>'+msg+'<message>');
   response.append('<internalError>'+internalError+'<internalError>');
   response.append('<response>');
   return Response.serverError().entity(response.toString()).build();
  }
 
 }

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

 @Path('{id}')
 @GET
 public Response getUserXMLById(@PathParam('id') Integer id) 
 {
  if(id==null || id < 1 ){
   throw new ApplicationException('User Id['+id+'] should not be less than 1.');
  }
  User user = userService.getById(id);
 
  if(user==null ){
   throw new ResourceNotFoundException('No User found with Id :['+id+']');
  }
  return Response.ok(user).build();
 }

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

 case 1 : GET http:localhost:8080resteasy-demorestusers0
  Response :
   <response>
                         <status>failed<status>
    <message>User Id[0] should not be less than 1.<message>
    <internalError>null<internalError>
   <response>
 
 case 2: GET http:localhost:8080resteasy-demorestusers100
  Response :
          <response>
           <status>failed<status>
    <message>No User found with Id :[100]<message>
   <response>

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>

RESTEasy Tutorial Series

RESTEasy Tutorial Part-1: Basics

RESTEasy Tutorial Part-2: Spring Integration

RESTEasy Tutorial Part 3 – Exception Handling

Reference: RESTEasy Tutorial Part 3 – Exception Handling from our JCG partner Siva Reddy at the My Experiments on Technology blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

One Response to "RESTEasy Tutorial Part-3: Exception Handling"

  1. Joe says:

    Remember that in step4a that your spring setup needs to scan the package of the class that is annotated with @Component.

Leave a Reply


+ eight = 12



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.