Node.js / Node.js Express Framework

Error Handling and Middleware in Express

This tutorial covers error handling in Express and the concept of middleware chaining. You'll learn how to catch and handle errors, and how to pass control between middleware func…

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Covers building web applications and REST APIs using the Express framework.

Tutorial: Error Handling and Middleware in Express.js

1. Introduction

In this tutorial, we aim to explore error handling and middleware in Express.js. Express.js is a fast, unopinionated, and minimalist web application framework for Node.js.

By the end of this tutorial, you will:

  • Understand how middleware works in Express.js
  • Learn how to handle errors in Express.js
  • Be able to develop middleware functions and use them for error handling

The prerequisites for this tutorial are a basic understanding of JavaScript and some familiarity with Node.js and Express.js.

2. Step-by-Step Guide

Understanding Middleware

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.

Middleware functions can perform the following tasks:

  • Execute any code
  • Make changes to the request and the response objects
  • End the request-response cycle
  • Call the next middleware function in the stack

Error Handling in Express

In Express, 404 responses are not the result of an error, so the error-handler middleware will not capture them. To handle a 404 response, add a middleware function at the end of the stack.

Errors that occur in synchronous code inside route handlers and middleware require no extra work. If synchronous code throws an error, then Express will catch and process it.

3. Code Examples

Basic Error Handling

app.use(function(err, req, res, next) {
  console.error(err.stack); // Log error message in our server's console
  res.status(500); // Announce that this is a 500 error
  res.send('Something broke!'); // Inform client about the error
});

In this example, app.use is used to setup middleware. We're passing a function that accepts four arguments to app.use. This function is an error handling middleware. Express identifies it as such and passes errors to it.

404 Handling

app.use(function(req, res, next) {
  res.status(404).send('Sorry cant find that!');
});

This middleware function does not have an error in its arguments, Express treats it as a regular middleware. You should ensure this comes after all your other routes because responses are sent in order.

4. Summary

In this tutorial, we have learned about error handling and middleware in Express.js. We've seen how Express uses middleware and how to create error handling middleware.

For further learning, consider exploring more about Express middleware, like built-in middleware, third-party middleware, and writing your own middleware functions.

5. Practice Exercises

  1. Create a middleware function that logs the current date and time each time a request is made to the server.
  2. Create an error handling middleware that responds with a custom error page.
  3. Create a middleware stack with at least three middleware functions, where each function logs something to the console and passes control to the next middleware function.

Tips: Always handle errors and be prepared for the unexpected. Remember, middleware functions that do not handle errors must take only three parameters. Otherwise, they might be mistaken for error handling functions.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

Robots.txt Generator

Create robots.txt for better SEO management.

Use tool

Unit Converter

Convert between different measurement units.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help