RESTEasy ExceptionMapper – Exception handling example

Learn to create and handle custom exceptions using resteasy ExceptionMapper interface implementations. ExceptionMapper is a contract for a provider that maps Java exceptions to Response object.

An implementation of ExceptionMapper interface must be annotated with @Provider to work correctly.

1. Resteasy ExceptionMapper – Custom exception handler

A sample implementation provider class of ExceptionMapper looks like this:

package com.howtodoinjava.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;

@Provider
public class MyApplicationExceptionHandler implements ExceptionMapper<MyApplicationException> 
{
	@Override
	public Response toResponse(MyApplicationException exception) 
	{
		return Response.status(Status.BAD_REQUEST).entity(exception.getMessage()).build();	
	}
}

Where the custom exception class MyApplicationException.java is written as:

package com.howtodoinjava.exception;

import java.io.Serializable;

public class MyApplicationException extends Exception implements Serializable
{
	private static final long serialVersionUID = 1L;

	public MyApplicationException()	{
		super();
	}
	public MyApplicationException(String msg)	{
		super(msg);
	}
	public MyApplicationException(String msg, Exception e)	{
		super(msg, e);
	}
}

2. Resteasy REST API

To test the ExceptionMapper implementation, I have written following resteasy REST API.

package com.howtodoinjava.rest;

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

import org.jboss.resteasy.spi.validation.ValidateRequest;

import com.howtodoinjava.exception.MyApplicationException;

@Path("/rest")
public class UserService 
{
	@Path("/users/{id}")
	@GET
	@ValidateRequest
	public Response getUserBId	( @PathParam("id") String id ) throws MyApplicationException
	{
		//validate mandatory field
		if(id == null)
		{
			throw new MyApplicationException("id is not present in request !!");
		}
		//Validate proper format
		try
		{
			Integer.parseInt(id);
		}
		catch(NumberFormatException e)
		{
			throw new MyApplicationException("id is not a number !!");
		}
		//Process the request
		return Response.ok().entity("User with ID " + id + " found !!").build();
	}
}

3. RESTEasy ExceptionMapper demo

Above API accepts the user 'id' parameter in Integer format. If we pass the id in some other format which can not be parsed to Integer, it will throw MyApplicationException. Our exception mapper should be able to handle this.

3.1. Valid request

Access http://localhost:8080/RESTEasyExceptionMapperDemo/rest/users/1 in browser.

Valid request to REST API
Valid request to REST API

3.2. Invalid request – throws exception

Access http://localhost:8080/RESTEasyExceptionMapperDemo/rest/users/abc in browser.

Invalid request to REST API
Invalid request to REST API

To download the sourcecode of this example of Resteasy client exception handling with ExceptionMapper inreface, follow below given link.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

21 thoughts on “RESTEasy ExceptionMapper – Exception handling example”

  1. @Provider
    public class ExceptionHttpStatusResolver implements ExceptionMapper<EmptyException> {
     
    	@Override
        public Response toResponse(EmptyExceptionexception) {
            Response.Status httpStatus = Response.Status.INTERNAL_SERVER_ERROR;
     
            if (exception instanceof EmptyException)
                httpStatus = Response.Status.BAD_REQUEST;
     
            return Response.status(httpStatus).entity(exception.getMessage()).build();
        }
    } 
    Reply
  2. ExceptionMapper is not working, I am getting the full stack trace as a response with INTERNAL SERVER ERROR and not the appropriate message and status code

    Reply
  3. can you tell me how to write Java client for this instead of showing the exception message in browser… please provide me ASAP…

    Reply
  4. I am sending JSONObject to service and service is returning JSONObject to client.
    How to read custom defined error message at client side.

    Reply
  5. I have added mappers to my service written using Apache CXF. My problem is how to integration test my APIs. For e.g. is it possible to use Spring MVC mock with CXF.

    If there is any Validation failure in my service, then mapper will catch IllegalArgumentException and return response. It becomes impossible to catch the response in this case because the error handling was done by mapper and not the service,.

    Reply
  6. This setup does not work with UnrecognizedPropertyException, somehow this class is unreachable despite being in the classpath, can you provide some details on this?

    Reply
      • No error logs needed, just replace MyApplicationException with UnrecognizedPropertyException, you may notice org.jboss.resteasy.resteasy-jaxrs is not placing jackson-mapper-asl in your eclipse classpath, but if you indeed can import the class, if you run it, the MyApplicationExceptionHandler class instance is never called when UnrecognizedPropertyException is thrown and you’ll get your error log. I believe this problem is with org.jboss dependency and not codehaus.

        you may also want to try using jboss bom also, the problem could be there, theres is no point in including all this libreries when jboss already provides them in AS7.1.

        
        
                
        		org.jboss.spec
        	        jboss-javaee-all-7.0
        		1.0.0.Final
        	        pom
        	        import
        	
        
        
        
                
        	        org.jboss.spec.javax.ws.rs
        	        jboss-jaxrs-api_1.1_spec
        	        provided
                
        
                
                    org.jboss.resteasy
                    resteasy-jaxrs
                    provided
                
                
                
                    org.jboss.resteasy
                    resteasy-jackson-provider
                    provided
                
        
        

        let me know if you had any troubles finding this dependency issue with jboss resteasy and jackson provider

        Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.