Handling Errors with Middleware

Tutorial 4 of 5

Handling Errors with Middleware

1. Introduction

The goal of this tutorial is to guide you through the process of handling errors in an Express.js application using error handling middleware.

By the end of this tutorial, you will learn how to:

  • Understand the concept of middleware in Express.js
  • Use built-in error handling middleware
  • Implement custom error handling middleware

Prerequisites: To get the most out of this tutorial, you should have a basic understanding of JavaScript and Node.js. Familiarity with Express.js will be helpful but is not mandatory.

2. Step-by-Step Guide

Middleware functions in Express.js 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.

Error handling middleware specifically handles errors that occur during the execution of route handlers and middleware.

Built-in Error Handling

Express.js comes with a default error handling middleware function. All you need to do is add a middleware function with four arguments instead of three (err, req, res, next). The err argument represents the error object.

Custom Error Handling

You can also create custom error handling middleware for more specific error handling needs. The process is similar to using the built-in error handler, but you get to define the behavior of the error handler.

3. Code Examples

Example 1: Using built-in error handling middleware

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

app.get('/', (req, res, next) => {
  // Intentionally cause an error
  throw new Error('Something went wrong!');
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('An error occurred!');
});

app.listen(3000, () => {
  console.log('App is listening on port 3000');
});

In this example, we intentionally throw an error in our route handler. The error handling middleware catches this error, logs the error stack and sends a response with status code 500 and a custom error message.

Example 2: Implementing a custom error handling middleware

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

app.get('/', (req, res, next) => {
  // Intentionally cause an error
  throw new Error('Something went wrong!');
});

// Custom Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    status: 'error',
    message: err.message
  });
});

app.listen(3000, () => {
  console.log('App is listening on port 3000');
});

In this example, we create a custom error handling middleware that returns a JSON response with a status and error message.

4. Summary

We have learned the concept of middleware in Express.js and how to implement error handling using both built-in and custom error handling middleware. As a next step, you can explore more about the Express.js framework and its features.

5. Practice Exercises

  1. Create an Express.js application with at least two routes. Intentionally cause an error in one of the routes and handle it using built-in error handling middleware.

  2. Now, modify your application to handle the error using a custom error handling middleware.

  3. Create a custom error handling middleware that logs errors to a file instead of the console.

Remember, practice is key to mastering any concept. Happy coding!