有没有办法以某种方式全局处理servlets抛出的osgi (karaf)中的未检查异常?
我的意思是类似于Spring,其中有@ControllerAdvice,您可以为每种异常类型指定方法并处理它。
我想统一我的rest api中的异常处理,它公开了osgi服务。
发布于 2018-11-15 00:12:31
在OSGi中执行REST
您在这个问题中提到了REST和Servlets。如果您在OSGi中使用REST,那么JAX-RS白板是最简单的方法。如果您想使用原始的Servlets,那么Http白板是最佳选择。这两种模型都使得处理异常变得很容易。
更新
为了让人们更容易了解它是如何工作的,我创建了一个工作示例on GitHub,它涵盖了Servlets和JAX-RS错误处理。
使用HTTP白板
HTTP白板允许servlets注册为OSGi服务,然后用于处理请求。请求处理的一种类型是充当错误页面。
使用osgi.http.whiteboard.servlet.errorPage属性注册错误页。此属性的值是一个或多个字符串,其中包含以下内容之一:
OSGi规范describes this in an example和其他页面list the attributes,您可以使用它们来找出哪里出了问题。
例如,对于IOException、NullPointerException以及状态代码401和403,将调用此servlet
@Component
@HttpWhiteboardServletErrorPage(errorPage = {"java.io.IOException", "java.lang.NullPointerException", "401", "403"})
public class MyErrorServlet extends HttpServlet implements Servlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws Exception {
Throwable throwable = (Throwable) request
.getAttribute("javax.servlet.error.exception");
Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
// Do stuff with the error
}
}注意:我使用了OSGi R7元件特性类型注释来使其更易于阅读。它将与旧版本的DS和Http白板一样好用。
使用JAX-RS白板
JAX-RS白板allows you to use any of the JAX-RS extension types as a whiteboard service。在本例中,您需要一个ExceptionMapper。
在本例中,我们为IOException添加了一个处理程序
@Component
@JaxrsExtension
public class MyExceptionMapper implements ExceptionMapper<IOException> {
Response toResponse(IOException e) {
// Create a response
}
}https://stackoverflow.com/questions/53302695
复制相似问题