Express.js / Middleware in Express.js

Handling Errors with Middleware

This tutorial explains how to handle errors in an Express.js application using error handling middleware.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers the role of middleware in Express and its different types.

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!

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

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

MD5/SHA Hash Generator

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

Use tool

Robots.txt Generator

Create robots.txt for better SEO management.

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