Wednesday, October 26, 2011

A simple tutorial about Exception handling in Jersey 1.1.5

There are at least three ways for us to deal with Exception in Jersey RESTful framework.

  1. Create a WebApplicationException instance and throw it in code.
  2. Extending your own Exception from WebApplicationException and throw your own exception in code
  3. creating an ExceptionMapper to have chance to further customize response upon exception.

This simple tutorial shows how to map our own defined exception in Jersey. Code has been created and tested in netbeans 6.9.1 with Jersey version 1.1.5 and Tomcat 6.

creating our dummy runtime exception class

package jia.blog;

public class JiaAppException extends RuntimeException{

    public JiaAppException( String message ) {
        super( message );
    }

}

Create our testing Web service

package jia.blog;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;

/**
 * REST Web Service
 *
 * @author Yiyu Jia
 */

@Path("generic")
public class WSTester {
    @Context
    private UriInfo context;

    /** Creates a new instance of WSTester */
    public WSTester() {
    }

    /**
     * Retrieves representation of an instance of jia.blog.WSTester
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("application/xml")
    public String getXml() {        
         throw new JiaAppException("Sorry. You are not allowed to access this resource.");
    }

}

Creating Exception Mapper class

package jia.blog;

import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

/**
 *
 * @author Yiyu Jia
 */

@Provider
public class JiaExceptionMapper implements ExceptionMapper< jiaappexception > {

    @Override
    public Response toResponse(JiaAppException jiaException) {
        
        GenericEntity ge = new GenericEntity < string > ( jiaException.getMessage ( ) ) { };

        return Response.status(Response.Status.FORBIDDEN).
                entity(ge).build();
    }
}


The web.xml file

Note: no servlet init param 'com.sun.jersey.config.property.packages'

    
        ServletAdaptor
        com.sun.jersey.spi.container.servlet.ServletContainer       
        1
    
    
        ServletAdaptor
        /resources/*
    
    
        
            30
        
    
    
        index.jsp
    


Test it

If you deploy web app on tomcat running on localhost and listen on port 8080, you test by pointing web browser to access URL http://localhost:8080/JerseyTest/resources/generic .

No comments:

Post a Comment