Global Exception Handling in Jersey

前端 未结 3 1088
耶瑟儿~
耶瑟儿~ 2021-02-01 14:01

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

相关标签:
3条回答
  • 2021-02-01 14:06

    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();
      }
    }
    
    0 讨论(0)
  • 2021-02-01 14:09

    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

    0 讨论(0)
  • 2021-02-01 14:17

    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

    0 讨论(0)
提交回复
热议问题