Skip to content
Ned edited this page Dec 26, 2021 · 1 revision

Custom Error Route

Vex provides an easy way to override the default route for errors (e.g. page not found, internal server error, etc.) Just simply change the on_error value of the instance of the Router (a.k.a app variable or similar). To extract the status code, simply cast the request context to int.

mut app := router.new()
app.on_error = fn (req &ctx.Req, mut res ctx.Resp) {
    code := int(req.ctx)
    match code {
      404 { res.send('Oh no! The page was not found!', code) }
      500 { res.send('Something went wrong with the server.', code) }
      // ...
      else { res.send('Unknown error.', code) }
    } 
}

app.route(.get, '/', fn (req &ctx.Req, mut res ctx.Resp) {
    res.send('Hello world!', 200)
})

server.serve(app, 8080)
Clone this wiki locally