Global Exception Handling in Jersey

前端 未结 3 1127
耶瑟儿~
耶瑟儿~ 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 {
      public Response toResponse(javax.persistence.EntityNotFoundException ex) {
        return Response.status(404).
          entity(ex.getMessage()).
          type("text/plain").
          build();
      }
    }
    

提交回复
热议问题