Node.js / Node.js Error Handling and Debugging

Using Error Middleware in Express Applications

In this tutorial, we'll dive deep into using error middleware in Express, a popular Node.js framework. You'll learn how to use error middleware to centralize your error handling l…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers techniques for error handling and debugging Node.js applications.

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.

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

Meta Tag Analyzer

Analyze and generate meta tags for SEO.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

Fake User Profile Generator

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

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

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