首页 > 解决方案 > 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();
      }
    });

标签: javavert.x

解决方案


routingContext.fail()上下文再次失败,因此它会导致无限循环始终执行/api/job/:id. 如果要执行下一个失败处理程序(在本例中为路由器的 400 错误处理程序),则必须调用routingContext.next()

如果您需要对端点进行特定的错误处理/api/job/:id,请使用特定的故障处理程序并编写响应。如果您不需要任何特定的错误处理,并且只想对错误 400 使用通用错误处理,请在router.errorHandler()不向端点添加任何特定故障处理程序的情况下使用


推荐阅读