41

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.

4

3 回答 3

42

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

于 2012-06-08T21:46:16.783 回答
5

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();
  }
}
于 2016-04-21T15:58:18.837 回答
0

以上所有答案仍然有效。但是对于最新版本的 Spring Boot,请考虑以下方法之一。

方法 1:@ExceptionHandler- 使用此注解在控制器中注解一个方法。

这种方法的缺点是我们需要在每个控制器中编写一个带有此注解的方法。

我们可以通过使用基本控制器扩展所有控制器来解决此解决方案(该基本控制器可以有一个使用@ExceptionHandler 注释的方法。但这可能并非总是可行。

方法2:

  • 使用 @ControllerAdvice 注释类并使用 @ExceptionHandler 定义方法

  • 这类似于基于控制器的异常(参见方法 1),但在控制器类不处理异常时使用。这种方法有利于在 Rest Api 中全局处理异常

于 2020-01-21T01:49:36.797 回答