Jersey exception handling – Jersey ExceptionMapper Example

In Jersey ExceptionMapper example, we will learn to handle custom exceptions using ExceptionMapper interface while developing Jersey RESTful web services. For demo purpose, I am modifying the sourcecode written for jersey download file example.

Table Of Contents

1. Jersey custom exception with ExceptionMapper
2. How to throw exception from REST API
3. Demo

1. Jersey ExceptionMapper – Create custom exceptions

To handle custom exception in JAX-RS based web services, you should create an exception class and then implement the ExceptionMapper interface.

package com.howtodoinjava.jersey;

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

@Provider
public class MissingFileException extends Exception implements
				ExceptionMapper<MissingFileException> 
{
	private static final long serialVersionUID = 1L;

	public MissingFileException() {
		super("No File found with given name !!");
	}

	public MissingFileException(String string) {
		super(string);
	}

	@Override
	public Response toResponse(MissingFileException exception) 
	{
		return Response.status(404).entity(exception.getMessage())
									.type("text/plain").build();
	}
}

2. How to throw exception from REST API

Now you can throw MissingFileException when ever user requested file is not found in desired location.

package com.howtodoinjava.jersey;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

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

@Path("/download")
public class JerseyService 
{
	@GET
	@Path("/{fileName}")
	public Response downloadPdfFile(final @PathParam("fileName") String fileName) throws MissingFileException
	{
		final String fullFilePath = "C:/temp/" + fileName;
		
		File file = new File(fullFilePath);
		
		if(file.exists() == false){
			throw new MissingFileException(fileName + " does not existing on this server !!");
		}
		
		StreamingOutput fileStream =  new StreamingOutput()
		{
			@Override
			public void write(java.io.OutputStream output) throws IOException
			{
				try 
				{
					java.nio.file.Path path = Paths.get(fullFilePath);
					byte[] data = Files.readAllBytes(path);
					output.write(data);
					output.flush();
				} 
				catch (IOException e) 
				{
					throw new IOException("Error while reading file :: '"+fileName+"' !!");
				}
			}
		};
		return Response
	            .ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
	            .header("content-disposition","attachment; filename = '"+fileName)
	            .build();
	}
}

3. Jersey exception handling example

Now is the time to test jersey exceptionmapper. Now let’s see what happens when a file not found.

3.1. When user asks for correct file

No exception when file is found
No exception when file is found

3.2. When user asks for unknown file

404 with custom message when file is not found
404 with custom message when file is not found

3.3. Uncaught Exception Handling

If you want to handle all uncaught exception before going to user screen, you will have to map the Throwable itself.

package com.howtodoinjava.jersey.provider;

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

@Provider
public class UncaughtException extends Throwable implements ExceptionMapper<Throwable>
{
    private static final long serialVersionUID = 1L;
 
    @Override
    public Response toResponse(Throwable exception)
    {
        return Response.status(500).entity("Something bad happened. Please try again !!").type("text/plain").build();
    }
}

Drop me your questions related to this jaxrs exceptionmapper example.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

7 thoughts on “Jersey exception handling – Jersey ExceptionMapper Example”

  1. I’m using spring-boot-starter-jersey (2.2.1.RELEASE) and have strange behavior:
    i do
    WebApplicationException(“Some error description”, Response.Status.BAD_REQUEST);
    but I got
    {
    “timestamp”: 1585000844325,
    “status”: 400,
    “error”: “Bad Request”,
    “message”: “Bad Request”,
    “path”: “/api/test”
    }
    i.e. my “message” is ignored – can suggest why? Thanks for reply)

    Reply
  2. I want to create a exceptionHandler class that handles all the custom exceptions, like MyAppException1, MyAppException2 and MyAppException3. How to do it??

    Reply
    • I think , you can have a superclass that extends exception for all your custom exception classes and handle that using the exceptionmapper of that type

      Reply
  3. Hi,
    I’ve created a web service using Jersey which uses a standard API from Oracle EPM HFM. This API has a throwable exception called HFMEXception which is a subclass of standard java class Exception.. I would like to handle this exception before it gets to the Tomcat server, At present I have created a new ExceptionMapper class specifically for the HFMException and have added this class in the web.xml file. When I run the web service the tomcat message is still being displayed which means that my ExceptionMapper class is not being triggered. Any ides what I have done wrong – let me know if you need me to post any of my code?
    Thanks in advance

    Reply
  4. Let’s say I am creating two exception mapper.one with IOException and other with FileNotFoundException , then which will be called ?

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.