[JAX-RS] ExceptionMapper example (Maven + Jersey + Glassfish)

Create a new Maven project (Web app archetype) in eclipse and add the dependencies on jersey. Also you will need Glassfish server.
1. pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<name>rsexampleresponse Maven Webapp</name>

2. Main Application

package com.vvirlan;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import com.vvirlan.exception.IllegalArgumentExceptionMapper;
import com.vvirlan.resources.ExceptionResource;
import com.vvirlan.resources.HelloResource;

public class ApplicationMain extends Application {

	public Set<Class<?>> getClasses() {
		Set<Class<?>> classes = new HashSet<Class<?>>();
//Note that you need to add the exception mapper here, otherwise, it won't work
		return classes;

3. An example service

package com.vvirlan.resources;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

public class ExceptionResource {
//This is the default implementation	
	public Response getException () {
		throw new WebApplicationException(Response.Status.CONFLICT);
//Throw the IllegalArgument and it will get mapped automatically to whatever you define in the mapper (next class)
	public Response getIllegal() {
		throw new IllegalArgumentException();

4. The Exception Mapping class. Here we’re mapping the IllegalArgumentException to a BAD_REQUEST

package com.vvirlan.exception;

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

public class IllegalArgumentExceptionMapper implements ExceptionMapper<IllegalArgumentException> {

	public Response toResponse(IllegalArgumentException arg0) {
		return Response.status(Status.BAD_REQUEST).build();



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s