Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Exception Handling in Jersey

Tags:

java

rest

jersey

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.

like image 611
Trisfall Avatar asked Jun 08 '12 20:06

Trisfall


People also ask

What is global exception handling?

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.

How do you globally handle exceptions in spring boot?

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.

What is exceptions handling with example?

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.


2 Answers

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

like image 123
Martin Matula Avatar answered Sep 28 '22 07:09

Martin Matula


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();   } } 
like image 30
AlikElzin-kilaka Avatar answered Sep 28 '22 06:09

AlikElzin-kilaka