cyberwombat
cyberwombat

Reputation: 40133

403/Forbidden error custom page with Express 3 / Node

How can I create a route that will handle 403 errors from Express? I have default routes to catch 404/500 but it seems to stop before ever going to the router. Just stack dumps to screen.

Upvotes: 5

Views: 6525

Answers (1)

hunterloftis
hunterloftis

Reputation: 13809

To catch errors in express, use middleware that has four arguments:

app.use(handleErrors);

function handleErrors(err, req, res, next) {
  res.send('This is your custom error page.');
}

To ensure the error is a 403 error, you can do something like:

app.use(handle403);

function handle403(err, req, res, next) {
  if (err.status !== 403) return next();
  res.send('403 error');
}

Upvotes: 6

Related Questions