If we would like to limit the access to our app, we could write a middleware for that too! This example only grants you access on thrusdays, but a real world example could, for example, be user authentication. A good place to put this would be after the logging middleware but before any content is sent.
app.use(function (req, res, next) {
if (new Date().getDay() !== 4) {
next('Access is only granted on thursdays')
} else {
next()
}
})
As you can see in this example, sending an error is as easy as providing a prameter to the next()
function.
Now, if we visit the website on any day different than a thursday we would be greeted with a 500 error and the string 'Access is only granted on thursdays'
.
Now, this isn't good enough for our site. We would rather send the user a HTML message in another middleware:
app.use(function (err, req, res, next) {
res.end(`<h1>Error</h1><p>${err}</p>`)
})
This works kind of like a catch block: any error in the middleware prior to the error middleware will be sent to the former. An error middleware is identified by its 4 parameters.
You could also use the error middleware to recover from the error by calling the next method again:
app.use(function (err, req, res, next) {
// Just joking, everybody is allowed access to the website!
next()
})