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.

3.2. Invalid request – throws exception
Access http://localhost:8080/RESTEasyExceptionMapperDemo/rest/users/abc
in browser.

To download the sourcecode of this example of Resteasy client exception handling with ExceptionMapper inreface, follow below given link.
Happy Learning !!
It is configuration issue. Please verify your configurations.
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/
Hi Lokesh, Can we reuse Rest API ExceptionMapper designed for a Rest API by a Coral-RPC API ? Please reply this question.
Haven’t worked on coral framework.
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
can you tell me how to write Java client for this instead of showing the exception message in browser… please provide me ASAP…
I am sending JSONObject to service and service is returning JSONObject to client.
How to read custom defined error message at client side.
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?
Above link is not working it’s occurred 404 error
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,.
HTML tags are coming in data with customised message.So please can u tell what will be the reason
You will get only what you return from API. You must be trying to view source of a webpage.
Actually it was not calling exception handler and it is taking system generated exception
This setup does not work with UnrecognizedPropertyException, somehow this class is unreachable despite being in the classpath, can you provide some details on this?
Can you please share the error logs.
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.
let me know if you had any troubles finding this dependency issue with jboss resteasy and jackson provider
Nice Post! thanx 🙂
If we dont pass any value in “id” it dont catch that exception and return 404 error.
How to handle this excaption
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.
Fits perfect, thank you!