java - Vert.x 中的 REST 验证处理
问题描述
我正在按照官方文档中的示例进行操作,但我无法弄清楚错误处理是如何工作的。
如果我routingContext.fail(400)
从路由处理程序中执行此操作,它将进入无限循环。如果我不这样做,则不会调用路由器处理程序。
路由处理程序
HTTPRequestValidationHandler validationHandler = HTTPRequestValidationHandler.create().addPathParam("id", ParameterType.UUID);
router.get("/api/job/:id")
.handler(validationHandler)
.handler(jobController::getJob)
.failureHandler((routingContext) -> {
Throwable failure = routingContext.failure();
if (failure instanceof ValidationException) {
// Something went wrong during validation!
String validationErrorMessage = failure.getMessage();
//routingContext.fail(400);
}
});
路由器处理程序
router.errorHandler(400, routingContext -> {
if (routingContext.failure() instanceof ValidationException) {
final JsonObject error = new JsonObject()
.put("timestamp", System.nanoTime())
.put("error", routingContext.failure().getMessage())
.put("exception", routingContext.failure().getStackTrace().toString());
routingContext.response().setStatusCode(400).end(error.encode());
} else {
// Unknown 400 failure happened
routingContext.response().setStatusCode(400).end();
}
});
解决方案
routingContext.fail()
上下文再次失败,因此它会导致无限循环始终执行/api/job/:id
. 如果要执行下一个失败处理程序(在本例中为路由器的 400 错误处理程序),则必须调用routingContext.next()
如果您需要对端点进行特定的错误处理/api/job/:id
,请使用特定的故障处理程序并编写响应。如果您不需要任何特定的错误处理,并且只想对错误 400 使用通用错误处理,请在router.errorHandler()
不向端点添加任何特定故障处理程序的情况下使用
推荐阅读
- activemq-artemis - 30k 地址/队列的 ActiveMQ Artemis Producer 性能问题
- html - 根据当前表单状态在Angular 7+中以交互方式禁用表单提交按钮的最佳方法是什么?
- python - 在熊猫中按组填充缺失日期的有效方法?
- angularjs - ng-attr 插值不适用于 ng-repeat
- matlab - 这条线在 Matlab 中是什么意思?
- java - 无法为 JAR 项目创建测试?
- python-3.x - 什么类型的数据作为参数接收来自 sklearn 的 LinearRegression 实例的方法预测?
- mysql - 单选中的列选择和变量分配
- r - R中的分组条形图显示类别中总数的百分比为高度,颜色为因子,每组为一列数据
- mongodb - 在 MongoDB 中将 java.net.URI 对象持久化为字符串