【发布时间】:2019-11-16 18:01:52
【问题描述】:
我正在关注官方文档中的example,但我无法弄清楚错误处理的工作原理。
如果我从路由处理程序中执行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();
}
});
【问题讨论】: