Arvind Katte
Arvind Katte

Reputation: 1003

WebApplicationException v/s ExceptionMapper in RESTful (Jersey) Web Service

I'm learning REST web service. I need some clarification on handling custom exception in Jersey. By using WebApplicationException and ExceptionMapper you can throw custom Exception. My question is in which scenario we have go for WebApplicationException and ExceptionMapper. What are the differences between them?

I've gone through with some tutorial, I found that ExceptionMapper is like Generic.

@Provider
class MyWrapper implements ExceptionMapper<MyPojoClass>
{
}

One more difference is that,

Because of @Provider Jersey will catch this exception only by default, if any other exception occurs also.

Is there any other differences?

MyExceptionMapper.java

package com.katte.galaxe.exception;

import javax.ws.rs.core.MediaType;
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;


public class MyExceptionMapper implements ExceptionMapper<MyCustomException>
{

@Override
public Response toResponse(MyCustomException errMsg) {
    ErrorMessage msg = new ErrorMessage(errMsg.getMessage(),1100);
    return Response.status(Status.NOT_FOUND)
            .type(MediaType.APPLICATION_XML)
            .entity(msg)
            .build();
}
}

MyWebApplicationException.java

package com.katte.galaxe.exception;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

public class MyWebApplicationException extends WebApplicationException{

private static final long serialVersionUID = -5788907118191114665L;

public MyWebApplicationException(ErrorMessage msg) {
    super(Response.status(Status.NOT_FOUND)
            .entity(msg)
            .type(MediaType.APPLICATION_XML)
            .build());
}
}

Upvotes: 2

Views: 2189

Answers (1)

Dhruvil Vaghela
Dhruvil Vaghela

Reputation: 590

WebApplicationException and ExceptionMapper are not meant to be compared as they serve different purpose. Instead they are meant to be used together for a better response strategy.

Imagine a case wherein an exception is encountered while serving a request. Let's say you encountered a SQLException while accessing a database. In this case one can make use of ExceptionMapper to map SQLException with an appropriate 5xx response instead of propagating the original exception to the end user.

WebApplicationException

Runtime exception for applications.

This exception may be thrown by a resource method, provider or StreamingOutput implementation if a specific HTTP error response needs to be produced. Only effective if thrown prior to the response being committed.

ExceptionMapper

Contract for a provider that maps Java exceptions to Response.

Upvotes: 2

Related Questions