Is there a way to have global exception handling in Jersey? Instead of individual resources having try/catch blocks and then calling some method that then sanitizes all of the exceptions to be sent back to the client, I was hoping there was a way to put this where the resources are actually called. Is this even possible? If so, how?
Instead of, where sanitize(e)
would throw some sort of Jersey-configured exception to the Jersey servlet:
@GET public Object getStuff() { try { doStuff(); } catch (Exception e) { ExceptionHandler.sanitize(e); } }
Having:
@GET public Object getStuff() throws Exception { doStuff(); }
where the exception would get thrown to something that I can intercept and call sanitize(e)
from there.
This is really just to simplify all the Jersey resources and to guarantee that the exceptions going back to the client are always in some sort of understandable form.
The Global Exception Handler is a type of workflow designed to determine the project's behavior when encountering an execution error. Only one Global Exception Handler can be set per automation project.
You can define the @ExceptionHandler method to handle the exceptions as shown. This method should be used for writing the Controller Advice class file. Now, use the code given below to throw the exception from the API. The complete code to handle the exception is given below.
Example: Exception handling using try...catch In the example, we are trying to divide a number by 0 . Here, this code generates an exception. To handle the exception, we have put the code, 5 / 0 inside the try block. Now when an exception occurs, the rest of the code inside the try block is skipped.
Yes. JAX-RS has a concept of ExceptionMappers. You can create your own ExceptionMapper interface to map any exception to a response. For more info see: https://jersey.github.io/documentation/latest/representations.html#d0e6352
javax.ws.rs.ext.ExceptionMapper is your friend.
Source: https://jersey.java.net/documentation/latest/representations.html#d0e6665
Example:
@Provider public class EntityNotFoundMapper implements ExceptionMapper<javax.persistence.EntityNotFoundException> { public Response toResponse(javax.persistence.EntityNotFoundException ex) { return Response.status(404). entity(ex.getMessage()). type("text/plain"). build(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With