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 !!

Comments

Subscribe
Notify of
guest
9 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.