Using Error Middleware in Express Applications

Tutorial 2 of 5

1. Introduction

In this tutorial, we will learn how to use error middleware in Express.js, a popular Node.js framework. Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

By the end of this tutorial, you'll understand how to:

  • Use error-handling middleware functions
  • Create custom error handling middleware
  • Implement centralized error handling in your Express app

Prerequisites:

  • Basic knowledge of JavaScript
  • Familiarity with Node.js and Express.js
  • Node.js and Express.js installed on your local machine

2. Step-by-Step Guide

Error handling middleware in Express has a different signature than regular middleware. It takes four arguments instead of three: (err, req, res, next).

Express recognizes this by the number of arguments your function takes. If it takes four, Express will treat it as an error handler.

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

The above middleware will handle any errors that occur in your app. The err parameter is an error object, and we can use console.error() to log the error stack trace.

3. Code Examples

Let's look at an example that uses error middleware to handle all errors that occur in the application.

const express = require('express');
const app = express();

app.get('/', function (req, res) {
  throw new Error('BROKEN') // Express will catch this on its own.
})

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

app.listen(3000)

In the above example, we simulate an error in the '/' route handler by throwing an error. This error is then caught by our error handling middleware, which logs the error and responds with a status code of 500 and a message of 'Something broke!'.

4. Summary

In this tutorial, we covered how to use error middleware in Express.js. We learned that error handling middleware functions are defined in the same way as other middleware functions, except that they have an extra argument, err.

5. Practice Exercises

  1. Create an Express application and simulate an error in one of your route handlers. Use error handling middleware to catch this error and respond with a status code of 500 and a custom error message.

  2. Modify the above application to log the error stack trace using console.error().

  3. Create a custom Error class in your Express application. Throw an instance of this custom error in one of your route handlers and catch it in your error handling middleware.

Solutions:

  1. The code will look similar to the example provided in the tutorial.

  2. In the error handling middleware, use console.error(err.stack) to log the error stack trace.

  3. Here's how you might create a custom error:

class CustomError extends Error {
  constructor(message) {
    super(message);
    this.name = "CustomError";
  }
}

app.get('/', function (req, res) {
  throw new CustomError('Something custom broke!')
})

app.use(function (err, req, res, next) {
  if (err instanceof CustomError) {
    console.error(err.stack)
    res.status(500).send(err.message)
  } else {
    next(err)
  }
})

In the above example, we've created a custom error class that extends the built-in Error class. In our '/' route handler, we throw an instance of our CustomError. In our error handling middleware, we check if the error is an instance of CustomError. If it is, we log the error and send a response with the error message. If it's not a CustomError, we pass it on to the next middleware function.