是否可以通过某种方式全局处理servlet中抛出的osgi(karaf)中未经检查的异常?
我的意思是像Spring
中那样,那里有@ControllerAdvice
,您可以在其中为每种异常类型指定方法并进行处理。
我想统一我的Rest api中公开的osgi服务的异常处理。
答案 0 :(得分:0)
您在此问题中提到了REST和Servlet。如果您在OSGi中使用REST,那么JAX-RS白板是做事的最简单方法。如果要使用原始Servlet,则可以使用Http Whiteboard。两种模型都可以轻松处理异常。
为了使人们更容易理解它的工作原理,我创建了一个有效的示例on GitHub,其中涉及Servlet和JAX-RS错误处理。
HTTP白板允许将servlet注册为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 Whiteboard很好地兼容。
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
}
}