Swift Express Server的“找不到页面/ 404处理程序”

时间:2022-10-10 09:18:34

I’m writing the simplest server via Swift Express

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

And I want to add custom handler for “url not found” so that if user write “/notFoundUrl” he will see something like that: “Url “notFoundUrl” not found, please go to home page”.

我想为“url not found”添加自定义处理程序,以便如果用户写“/ notFoundUrl”,他会看到类似的内容:“Url”notFoundUrl“找不到,请转到主页”。

I’ve added:

我已经添加:

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"]!])
}

But it’s not appropriate becouse:

但这不合适因为:

  • Order does matter.
  • 订单确实很重要。
  • I can’t return 404 error.
  • 我无法返回404错误。

So how to add custom “Page Not Found/404 handler” to Swift Express Server?

那么如何在Swift Express Server中添加自定义的“Page Not Found / 404处理程序”?

1 个解决方案

#1


2  

It much simpler than you are trying to do it.

它比你试图做的简单得多。

/// 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
    }
}

The full do can be found here: https://github.com/crossroadlabs/Express/blob/master/doc/gettingstarted/errorhandling.md

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

#1


2  

It much simpler than you are trying to do it.

它比你试图做的简单得多。

/// 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
    }
}

The full do can be found here: https://github.com/crossroadlabs/Express/blob/master/doc/gettingstarted/errorhandling.md

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