Step 36: Global Error Handler

Notice the following code snippet is repeated in every route handler!

  } catch (err) {
    const code = err.status || 500;
    res.status(code).json({
      status: code,
      message: err.message || `Internal Server Error!`,
    });
  }

Let’s create a global error handler to avoid duplicate code!

Add the following to the end of src/index.js right before the export statement!

// Global error handler!
app.use((err, req, res, next) => {
  if (err) {
    const code = err.status || 500;
    res.status(code).json({
      status: code,
      message: err.message || `Internal Server Error!`,
    });
  }
  next();
});

Then update every route handler in src/routes/bookmarks.js as follows:

  1. change (req, res) to (req, res, next)
  2. change the body of catch block to next(err);

Save the changes and rerun the test. All tests must pass!