Express JS error handling 🌩

Posted on: 2017-05-08

One of the first difficulties you can encounter when you start using Express, is how to handle errors well, especialy if you're using promises.

Here is one way to go. To understand it, remember that in Express, call the next function with an argument (next(new Error('Details about my error')) for example). When you do this, the next middleware capale of handling that argument will be used.

const express = require(`express`); const app = express(); app.use(`/`, (req, res, next) => { return Promise.reject(`something went wrong`) .then(() => { // of course this wont happen // ... }) .catch(next); }) app.use((req, res, next) => { // this middleware won't be called res.send(`Everything is fine`); }) app.use((err, req, res, next) => { console.log(err); res.status(500).send(`Your request could not be processed`); }) app.listen(3000, () => { console.log(`Example app listening on port 3000!`); })

Browsing http://localhost:3000/, we'll just see the message : Your request could not be processed.