Global Exception Handling in Jersey

2020-05-19 04:12发布

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.

标签: java rest jersey
3条回答
ら.Afraid
2楼-- · 2020-05-19 04:25

All the answers above are still valid. But with latest versions of spring Boot consider one of below approaches.

Approach 1 : @ExceptionHandler- Annotate a method in a controller with this annotation.

Drawback of this approach is we need to write a method with this annotation in each controller.

We can work around this solution by extending all controllers with base controller (that base controller can have a method annotated with @ExceptionHandler. But it may not be possible all the times.

Approach 2 :

  • Annotating a class with @ControllerAdvice and define methods with @ExceptionHandler

  • This is similar to Controller based exception (refer approach 1) but this is used when controller class is not handling the exception. This approach is good for global handling of exceptions in Rest Api

查看更多
孤傲高冷的网名
3楼-- · 2020-05-19 04:33

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();
  }
}
查看更多
Explosion°爆炸
4楼-- · 2020-05-19 04:45

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

查看更多
登录 后发表回答