Error handling
我们可以设置handler来处理请求,同样我们还可以设置handler处理route中的失败情况.
Failure handlers 通常是和处理普通handler的route一起工作.
例如,你可以提供一个failure handler只是用来处理某种特定路径下的或者某种特定HTTP method的失败.
这种机制就为你向应用程序的不同部分设置不同的failure handler了.
下面的例子演示了我们向/somepath/开始的路径和GET请求才会被调用的failure handler.
Route route = router.get("/somepath/*");route.failureHandler(frc -> {// This will be called for failures that occur// when routing requests to paths starting with// '/somepath/'});
如果handler中抛出异常Failure routing就会发生作用, 或者handler调用失败,向客户端发送一个失败的HTTP状态码信号.
如果我们从handler中捕获一个异常, 我们将会向客户端返回500的状态码.
在处理失败的时候, failure handler会被传递给routing context, 我们可以在该context中检索出当前的错误, 因此failure handler可以用于生成failure response。
Route route1 = router.get("/somepath/path1/");route1.handler(routingContext -> {// Let's say this throws a RuntimeExceptionthrow 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 - ForbiddenroutingContext.fail(403);});// Define a failure handler// This will get called for any failures in the above handlersRoute route3 = router.get("/somepath/*");route3.failureHandler(failureRoutingContext -> {int statusCode = failureRoutingContext.statusCode();// Status code will be 500 for the RuntimeException or 403 for the other failureHttpServerResponse response = failureRoutingContext.response();response.setStatusCode(statusCode).end("Sorry! Not today");});
