HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / RESTEasy / RESTEasy ExceptionMapper – Exception handling example

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.

Sourcecode Download

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Gaurav

    November 26, 2014

    @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();
        }
    } 
    • Lokesh Gupta

      November 27, 2014

      It is configuration issue. Please verify your configurations.

      • Preeti

        November 28, 2016

        Hi Lokesh, I am trying to use Exception Mapper. But it is throwing Internal Server Error. I have an Coral-rest API, for that I defined API structure in Model and implemented it similarly like Coral API. Now When I a trying to test my API. It always throw Internal Server error/

    • Preeti

      November 28, 2016

      Hi Lokesh, Can we reuse Rest API ExceptionMapper designed for a Rest API by a Coral-RPC API ? Please reply this question.

      • Lokesh Gupta

        November 29, 2016

        Haven’t worked on coral framework.

  2. Gaurav

    November 26, 2014

    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

  3. ravi

    August 6, 2014

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

  4. Hasini

    July 29, 2014

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

    • Lokesh Gupta

      July 30, 2014

      As I do not know the complete scenario so I will make a guess here. Will you able to use
      https://accounts.google.com/o/oauth2/v2/auth?client_id=721724668570-nbkv1cfusk7kk4eni4pjvepaus73b13t.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fdeveloper.android.com%2Foauth2callback&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdeveloperprofiles+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdeveloperprofiles.award+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgoogledevelopers&access_type=online&response_type=code&state=%7B%22csrf_token%22%3A+%221f48cb523f18423f5b9307ae73035652f1dd74893e81a373182667fb530fd8fa%22%2C+%22return_url%22%3A+%22https%3A%2F%2Fdeveloper.android.com%2Freference%2Forg%2Fjson%2FJSONObject%22%7D&prompt=none&auto_signin=True#JSONObject%28java.util.Map%29 .
      Put some error keys and your error messages in hashmap and create JSONObject with above constructor. Let me know it doesn’t help and why?

      • naidu

        February 6, 2016

        Above link is not working it’s occurred 404 error

  5. rahul

    May 23, 2014

    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,.

  6. Mahantesh Hoolikatti

    May 7, 2014

    HTML tags are coming in data with customised message.So please can u tell what will be the reason

    • Lokesh Gupta

      May 7, 2014

      You will get only what you return from API. You must be trying to view source of a webpage.

      • Mahantesh Hoolikatti

        May 13, 2014

        Actually it was not calling exception handler and it is taking system generated exception

  7. Jorge Morando

    March 6, 2014

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

    • Lokesh Gupta

      March 6, 2014

      Can you please share the error logs.

      • Jorge Morando

        March 6, 2014

        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

  8. Kalpesh Adhatrao

    January 22, 2014

    Nice Post! thanx 🙂

  9. Vikas

    December 10, 2013

    If we dont pass any value in “id” it dont catch that exception and return 404 error.
    How to handle this excaption

    • Lokesh Gupta

      December 10, 2013

      404 means resource not found. In other words, your API to handle the request was not located (i.e. not executed). You can’t do much here.

  10. R063R

    November 7, 2013

    Fits perfect, thank you!

Comments are closed on this article!

Search Tutorials

RESTEasy Tutorial

  • JAX-RS – Introduction
  • RESTEasy – JBoss
  • RESTEasy – Tomcat
  • RESTEasy – @Path
  • RESTEasy – HATEOAS
  • RESTEasy – SLF4J
  • RESTEasy – Log4j
  • RESTEasy – Download
  • RESTEasy – Upload (MultipartForm)
  • RESTEasy – Upload (HTTPClient)
  • RESTEasy – Custom Validation
  • RESTEasy – Hibernate Validator
  • RESTEasy – ContainerRequestFilter
  • RESTEasy – PreProcessorInterceptor
  • RESTEasy – JAXB XML
  • RESTEasy – Jettison JSON
  • RESTEasy – Jackson JSON
  • RESTEasy – ExceptionMapper

RESTEasy Client APIs

  • RESTEasy – java.net
  • RESTEasy – JAX-RS Client
  • RESTEasy – Apache HttpClient
  • RESTEasy – JavaScript API
  • RESTEasy – ResteasyClientBuilder

RESTEasy Best Practices

  • RESTEasy – Sharing Context Data
  • RESTEasy – Exception Handling
  • RESTEasy – ETag Cache control
  • RESTEasy – GZIP Compression
  • RESTful vs. SOAP

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)