Reputation: 842
I am trying to determine if it is possible to setup an interceptor like solution on a REST resource such that if an exception is thrown I can log the exception and change the response returned. I basically don't want to wrap all my REST resources with try/catch blocks. If a REST resource was managed I would just use an @Interceptor on all of my calls but since it is not managed that seems to be out of the question.
Upvotes: 2
Views: 834
Reputation: 15250
You can use an implementation javax.ws.rs.ext.ExceptionMapper
. Let's suppose that your code might throw a YourFancyException
from the resources. Then you can use the following mapper:
@Provider
public class YourFancyExceptionMapper
implements ExceptionMapper <YourFancyException> {
@Override
public Response toResponse(YourFancyException exception) {
return Response.status(Response.Status.BAD_REQUEST)
.entity(exception.getMessage()).build();
}
}
Don't forget to annotate the mapper with @Provider
and to make your resources methods to throw YourFancyException
.
Upvotes: 2