"Page Not Found / 404 Handler" for Swift Express Server

I am writing a simple server through Swift Express

And I want to add a custom handler for "url not found", so if the user writes "/ notFoundUrl", he will see something like this: "Url" notFoundUrl "was not found, go to the main page".

Ive 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 this is not appropriate:

  • Order matters.
  • I cannot return error 404.

So, how to add a custom “Page not found / 404 handler” to Swift Express Server ?

+4
source share
1 answer

, .

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

: https://github.com/crossroadlabs/Express/blob/master/doc/gettingstarted/errorhandling.md

+2

All Articles