Error handling

我们可以设置handler来处理请求,同样我们还可以设置handler处理route中的失败情况.

Failure handlers 通常是和处理普通handlerroute一起工作.

例如,你可以提供一个failure handler只是用来处理某种特定路径下的或者某种特定HTTP method的失败.

这种机制就为你向应用程序的不同部分设置不同的failure handler了.

下面的例子演示了我们向/somepath/开始的路径和GET请求才会被调用的failure handler.

  1. Route route = router.get("/somepath/*");
  2. route.failureHandler(frc -> {
  3. // This will be called for failures that occur
  4. // when routing requests to paths starting with
  5. // '/somepath/'
  6. });

如果handler中抛出异常Failure routing就会发生作用, 或者handler调用失败,向客户端发送一个失败的HTTP状态码信号.

如果我们从handler中捕获一个异常, 我们将会向客户端返回500的状态码.

在处理失败的时候, failure handler会被传递给routing context, 我们可以在该context中检索出当前的错误, 因此failure handler可以用于生成failure response

  1. Route route1 = router.get("/somepath/path1/");
  2. route1.handler(routingContext -> {
  3. // Let's say this throws a RuntimeException
  4. throw new RuntimeException("something happened!");
  5. });
  6. Route route2 = router.get("/somepath/path2");
  7. route2.handler(routingContext -> {
  8. // This one deliberately fails the request passing in the status code
  9. // E.g. 403 - Forbidden
  10. routingContext.fail(403);
  11. });
  12. // Define a failure handler
  13. // This will get called for any failures in the above handlers
  14. Route route3 = router.get("/somepath/*");
  15. route3.failureHandler(failureRoutingContext -> {
  16. int statusCode = failureRoutingContext.statusCode();
  17. // Status code will be 500 for the RuntimeException or 403 for the other failure
  18. HttpServerResponse response = failureRoutingContext.response();
  19. response.setStatusCode(statusCode).end("Sorry! Not today");
  20. });