vert.x - Vertx - 使用 Router failureHandler 处理异步调用中的错误
问题描述
我们最近在 Vertx 路由器中发现了failureHandler
我们认为它可以帮助我们摆脱所有重复的try-catch
障碍。但是,唉,似乎在回调中抛出的异常没有被failureHandler
.
示例:在下面,failureHandler
仅在第三种情况下调用:
// Get the user details
router.get("/user").handler(ctx -> {
ctx.response().headers().add("content-type", "application/json");
// some async operation
userApiImpl.getUser(ctx, httpClient, asyncResult -> {
// ctx.response().setStatusCode(404).end(); //1
// throw new RuntimeException("sth happened"); //2
ctx.fail(404); //3
});
});
// ============================
// ERROR HANDLER
// ============================
router.get("/user").failureHandler(ctx -> {
LOG.info("Error handler is in the action.");
ctx.response().setStatusCode(ctx.statusCode()).end("Error occurred in method");
});
- 这是预期的吗?
try-catch
我们能否以某种方式在路由器中为异步上下文中发生的异常声明一个全局变量?
解决方案
预计手动发送带有错误代码的响应不会触发故障处理程序。
它应该在以下情况下触发:
路由路径匹配
处理程序抛出异常或调用 ctx.fail()
这是一个例子:
Route route1 = router.get("/somepath/path1/");
route1.handler(routingContext -> {
// Let's say this throws a RuntimeException
throw new RuntimeException("something happened!");
});
Route route2 = router.get("/somepath/path2");
route2.handler(routingContext -> {
// This one deliberately fails the request passing in the status code
// E.g. 403 - Forbidden
routingContext.fail(403);
});
// Define a failure handler
// This will get called for any failures in the above handlers
Route route3 = router.get("/somepath/*");
route3.failureHandler(failureRoutingContext -> {
int statusCode = failureRoutingContext.statusCode();
// Status code will be 500 for the RuntimeException or 403 for the other failure
HttpServerResponse response = failureRoutingContext.response();
response.setStatusCode(statusCode).end("Sorry! Not today");
});
请参阅 Vert.x Web 文档的错误处理部分
推荐阅读
- python - 将 using 语句从 c# 转换为 python
- r - 相当于 purrr::map 中的 `break`
- python - ValueError:时间数据与格式不匹配(将部分字符串转换为时间)
- python - 一致地使用平均值添加对象
- python - matplotlib set_rmax 和 set_rticks 不起作用
- java - 需要对 Manager 和 Employee 类进行编码。如何在不破坏封装的情况下使它们对彼此“可见”?
- excel - 为什么我不能从另一个工作表的数据透视表中选择第一行数据范围?
- c# - 从异步方法填充数据绑定属性的最佳方法是什么?
- javascript - React - 在初始状态(外部构造函数)调用时成员函数不是函数
- flex-lexer - Flex 删除预定义宏