“无法找到页面/ 404处理程序”到Swift Express Server

Pet*_*kov 5 linux web swift swift2 swiftexpress

我正在通过Swift Express编写最简单的服务器

我想为“找不到网址”添加自定义处理程序,以便如果用户输入“ / notFoundUrl”,他将看到类似的内容:“找不到网址“ notFoundUrl”,请转到主页”。

我已经添加:

app.get("/:notFoundUrl+") { (request:Request<AnyContent>)->Action<AnyContent> in
   print(request.params["notFoundUrl"])
   return Action<AnyContent>.render("index", context: ["hello": "Page Not Found: " + request.params["notFoundUrl"]!])
}
Run Code Online (Sandbox Code Playgroud)

但这是不合适的,因为:

  • 顺序很重要。
  • 我无法返回404错误。

那么如何将自定义“找不到页面/ 404处理程序”添加到Swift Express Server

str*_*nik 2

它比你尝试做的要简单得多。

/// Custom page not found error handler
app.errorHandler.register { (e:ExpressError) in
    switch e {
    case .PageNotFound(let path):
        return Action<AnyContent>.render("404", context: ["path": path], status: .NotFound)
    default:
        return nil
    }
}
Run Code Online (Sandbox Code Playgroud)

完整的操作可以在这里找到:https://github.com/crossroadlabs/Express/blob/master/doc/gettingstarted/errorhandling.md