@Provider
public class RuntimeExceptionMapper implements ExceptionMapper<RuntimeException> {
private static final Logger LOGGER = Logger.getLogger(RuntimeExceptionMapper.class.getName());
@Override
public Response toResponse(final RuntimeException e) {
// taken from http://stackoverflow.com/questions/13716793/jersey-how-to-register-a-exceptionmapper-that-omits-some-subclasses
if (e instanceof WebApplicationException) {
return ((WebApplicationException) e).getResponse();
}
LOGGER.log(Level.WARNING, "RuntimeException occurred", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity("Sorry, something went wrong")
.build();
}
}
Jersey 1.x ExceptionMapper examples
TweetPosted on Saturday Oct 29, 2016 at 12:42PM in Technology
CAUTION: this posting is about Jersey 1.x which is obsoleted. If you use more modern JAX-RS implementation such as Jersey 2.x or above, please check if there are any better approaches.
JAX-RS (Jersey) provides a mechanism called ExceptionMapper which is an universal way to map an exception that thrown by a JAX-RS implementation itself or application code, to any HTTP response. In this posting, I’ll introduce some basic but useful usages of it that I have found.
ExceptionMapper for RuntimeException
When your resource method throw an Exception, say, an unintentional NullPointerException which caused by a bug or something, typically this produces a 500 Error page which created by your application container. You can catch, log those exceptions and produce a customer-friendly response with an ExceptionMapper which is something like following:
ExceptionMapper for NotFoundException
When your app receive a request which has no corresponding resource method, typically this produces a 404 Error page created by your container as well as an uncaught Exception. You can handle this situation with an ExceptionMapper as follows:
@Provider
public class NotFoundExceptionMapper implements ExceptionMapper<NotFoundException> {
private static final Logger LOGGER = Logger.getLogger(NotFoundExceptionMapper.class.getName());
@Override
public Response toResponse(final NotFoundException e) {
LOGGER.log(Level.FINE, "NotFoundException occurred", e);
return Response.status(Response.Status.NOT_FOUND)
.entity("Check the destination path of your request - we have no API here")
.build();
}
}
ExceptionMapper for ParamExceptionMapper
Let’s say you have a value class which is something like following:
public class EmployeeId {
private final long value;
public EmployeeId(final long value) {
if (value < 1) {
throw new IllegalArgumentException("EmployeeId must be larger than zero");
}
this.value = value;
}
public EmployeeId(final String value) {
this(Long.parseLong(value));
}
// getter and toString omitted
}
And you have a resource method which receives an EmployeeId
as follows:
@Path("myresource")
public class MyResource {
@GET
@Path("emp")
@Produces(MediaType.TEXT_PLAIN)
public String emp(@QueryParam("id") EmployeeId id) {
...
}
}
When the resource method receives a valid id
, say 123
, Jersey automatically constructs an EmployeeId
instance and passes it to the application code. That’s fine, but consider if a malicious user has sent an invalid value, say -1
. Typically this produces an error page which created by your container as well. You may want to return a more informational response with HTTP status code 400
with an ExceptionMapper which is something like:
@Provider
public class ParamExceptionMapper implements ExceptionMapper<ParamException> {
private static final Logger LOGGER = Logger.getLogger(ParamExceptionMapper.class.getName());
@Override
public Response toResponse(final ParamException e) {
LOGGER.log(Level.FINE, "ParamException occurred", e);
final StringBuilder sb = new StringBuilder("Your parameter '" + e.getParameterName() + "' is invalid");
final Throwable cause = e.getCause();
if (cause instanceof IllegalArgumentException) {
final String message = cause.getMessage();
if (message != null && !message.isEmpty()) {
sb.append(": ").append(message);
}
}
return Response.status(Response.Status.BAD_REQUEST)
.entity(sb.toString())
.build();
}
}
Conclusion
ExceptionMapper helps making error responses of your REST APIs more helpful. And it reduces repetitive exception handling code in your resource classes that tend to be tons of boilarplate.
You can obtain complete code based on Jersey 1.x and testcases that powered by Arquillian, Embedded Tomcat and Apache HttpClient, from my GitHub repository.
Tags: arquillian jax-rs jersey