2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there anyway to do this on a per method basis? I don't want it to change legacy resources. Also if I made this for "Exception" would it catch all exceptions?
It works on a "per exception" basis, not "per method", but the mapper catches only the exceptions thrown from the resource methods. So, it should not be a problem with legacy resources as they, I guess, already deal with the exception with a try/catch. Yes, it catches all exceptions (thrown from resource methods) if you use a mapper for Exception.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.