泽西岛的全局异常处理

2022-09-01 02:39:38

有没有办法在泽西岛进行全局异常处理?我希望有一种方法可以将此放在实际调用资源的位置,而不是单个资源具有 try/catch 块,然后调用某个方法,然后清理要发送回客户端的所有异常。这有可能吗?如果是这样,如何?

取而代之的是,哪里会向泽西岛 servlet 抛出某种泽西岛配置的异常:sanitize(e)

@GET
public Object getStuff() {
    try {
        doStuff();
    } catch (Exception e) {
        ExceptionHandler.sanitize(e);
    }
}

有:

@GET
public Object getStuff() throws Exception {
    doStuff();
}

其中异常将被抛出到我可以拦截并从那里调用的内容。sanitize(e)

这实际上只是为了简化所有泽西岛资源,并保证返回给客户端的异常始终以某种可理解的形式出现。


答案 1

是的。JAX-RS 有一个 ExceptionMappers 的概念。您可以创建自己的 ExceptionMapper 接口,以将任何异常映射到响应。有关详细信息,请参阅: https://jersey.github.io/documentation/latest/representations.html#d0e6352


答案 2

javax.ws.rs.ext.ExceptionMapper是你的朋友。

资料来源:https://jersey.java.net/documentation/latest/representations.html#d0e6665

例:

@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();
  }
}