Menu

ExpressJS has specific middleware for handling errors.

This middleware is inserted after the others and has the particularity of accepting an instance of the Error object as the first parameter.

app.use((error, req, res, next) => {

});

To trigger error handling within this middleware, we need to pass an Error object to the next() function of a route when a problem occurs.

app.post('/contact, async (req, res, next) => {
    try {
      const sent = await sendEmail(req.body);
      res.redirect('/thank-you');
    } catch(err) {
       const error = new Error(err);
         return next(error);
    }  
});

It is important to note that the function that raises the error must necessarily abort its execution via the return statement when calling the next() function by passing it the Error object.

In the middleware we can set the HTTP status with an error code and show an error page. So far our middleware has no way of knowing what kind of error was raised, so we need to modify the instance of the error by adding more information.

app.post('/contact, async (req, res, next) => {
    try {
      const sent = await sendEmail(req.body);
      res.redirect('/thank-you');
    } catch(err) {
       const error = new Error(err);
       error.httpStatus = 500;
       error.displayMessage = 'Error while sending the request.';
         return next(error);
    }  
});

Now our middleware can use this information to set the HTTP status and display the error page.

app.use((error, req, res, next) => {
    const { httpStatus, displayMessage } = error;
        res.status(httpStatus).render('errors/' + httpStatus, {
            title: 'Error ' + httpStatus,
            message: displayMessage
        });
});

Notice how the generation of the error page is completely dynamic as regards the view template to use and the message to show.

Share: