- Create a
WebApplicationException
instance and throw it in code. - Extending your own Exception from
WebApplicationException
and throw your own exception in code - 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
No comments:
Post a Comment