I've created a custom ExceptionMapper
that I wan' to call every time an exception occurs in the API to map it to a suitable response. The following is my custom exception class:
@Provider
public class ServiceExceptionMapper implements ExceptionMapper<Throwable> {
private Logger logging = LoggerFactory.getLogger(getClass());
@Override
public Response toResponse(Throwable throwable) {
log.error("There is an exception: ", throwable);
if (throwable instanceof IllegalArgumentException) {
return Response.status(Response.Status.BAD_REQUEST).entity(throwable.getMessage()).type (MediaType.TEXT_PLAIN).build();
}
if (throwable instanceof WebApplicationException) {
WebApplicationException we = (WebApplicationException) throwable;
return we.getResponse();
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(throwable.getMessage()).type(MediaType.TEXT_PLAIN).build();
}
}
Now, in my resource class, I have a try and a catch block. If there is an exception, the catch block should catch it and invoke the custom exception mapper class. Usual way of throwing an exception is the following:
catch (Exception e) {
throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity("Internal Server Error").build());
}
I'm trying to call the exception mapper class in the following way:
catch (Exception e) {
exceptionMapper.toResponse(e);
}
Where exceptionMapper
is a field of the class ServiceExceptionMapper
.