Wednesday, November 16, 2011

Using Exception Handlers in CXF

I was developing a web application and used Apache CXF for developing RESTful web-services. During the development we often come across scenarios where the expected entity does not exist in database. In RESTful web-services we form our own URLs to access the web-service and get the response. It is a common test scenario where one can try to access some data using such urls and that data may not be present in database at all.
For Example, lets see I am accessing company information using its name via webservice.

Say the URL looks like http://localhost:8080/resource/company/developmentCompany.


Lets say but the database does not contain any row for developmentCompany. Obviously the query will fail and end up throwing exception.


We can always handle such exceptions using null checks but it is more accurate to handle such exceptions using some ExceptionMappers which will show some User friendly message. In CXF, we can create our own ExceptionMappers to handle such scenarios in following way.


    Create your own Mapper class which will implement
     javax.ws.rs.ext.ExceptionMapper interface and use the actual exception  
    class as a parameter class to javax.ws.rs.ext.ExceptionMapper. Now your 
    mapper class needs to implement the method toResponse(E exception).

public class NoResultMapper implements ExceptionMapper<javax.persistence.noresultexception>{
  private static Logger logger = Logger.getLogger(NoResultMapper.class.getName());
  @Override
  public Response toResponse(NoResultException exception) {
  logger.warn("Result not found.. The entity does not exist in database." + exception.getCause() + ": " +                   
                                 exception.getMessage());
  return Response.serverError().entity(new GenericError("Result not found.. The entity does not exist in database.",   
  exception.getCause() + ": " + exception.getMessage())).build();
}

After creating your own mapper, you need to declare your mapper in your service beans xml file.

<bean id="noResultMapper" class="exceptionMappers.NoResultMapper" /> 

1 comment:

  1. Where is GenericError defined ? Is it your custom class ?

    If yes how does it get marshalled and then unmarshalled ?

    ReplyDelete