Should a jax-rs based framework use a single exception mapper?

时间:2017-08-04 12:56:09

标签: java jax-rs

We have a large legacy application to which we recently added jersey/jax-rs based functionality. The idea is that we will implement new functionality for our UI layer as restful APIs. A first prototype is working nicely - but it is lacking proper error handling.

I had a closer look at the initial implementation, and what I found is that there is a "base task" class that registers a specific ExceptionMapper. The idea is that there will be different and disjunct sub tasks extending that base task.

My initial thought was: each sub task should have its own, specific exception mapper.

In other words: I see two different options:

  • one central exception mapper, that works all exceptions thrown within any of the numerous sub tasks we are going to implement over time
  • one mapper per sub task

Option 1 leading to well, one central piece of code - but much less flexible compared to option 2 (it starts with things like: normally our sub tasks have their own "log id" when writing logs - but a central mapper doesn't know about its context and has to use the very same log id all the time).

My question is: are the hard technical facts (or well established "best procedures") to select between the two options?

2 个答案:

答案 0 :(得分:1)

在我看来,一个常规异常处理程序可以捕获所有内容public class GenericExceptionMapperProvider implements ExceptionMapper<Throwable>,并且您可以根据需要继续添加更多异常处理程序。

  

JAX-RS也支持异常继承。当有例外时   抛出,JAX-RS将首先尝试为此找到ExceptionMapper   异常的类型。如果找不到,它将寻找一个映射器   可以处理异常的超类。它会继续下去   进程,直到没有更多的超类来匹配。   read more

这是我写的帖子:http://blog.nafiux.com/posts/jax-rs-exception-handling/

答案 1 :(得分:0)

做了一些更多的研究。设计讨论,我意识到基本上我的问题走向了错误的方向:

  • 首先,不需要 catch-everything-mapper 。相反,可以扩展java.util.logging.Handler然后配置资源以使用org.glassfish.jersey.logging.LoggingFeature。
  • 来自那里的
  • :理想情况下,异常映射器应该这样做:将特定异常映射到某些预期的&#34;结果&#34;。

换句话说:我们的解决方案归结为

  • 使用&#34; logging&#34;泽西的能力记录任何传入的异常
  • 有一些通用的和一些&#34;每个组件&#34;例外地图制作者