Express.js / Error Handling in Express.js

Customizing Error Responses

This tutorial will show you how to customize error responses in Express.js. Customizing these responses can make your application's error messages more informative and user-friend…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers error handling strategies and best practices for Express applications.

Customizing Error Responses in Express.js

1. Introduction

Goal of this Tutorial

This tutorial aims to guide you on how to customize error responses in Express.js. By customizing error responses, you can provide more informative and user-friendly error messages.

What you will Learn

By the end of this tutorial, you will be able to create custom error messages that can assist in debugging and improve user experience.

Prerequisites

You should have a basic understanding of JavaScript and some experience using Express.js.

2. Step-by-Step Guide

Error handling in Express.js is done using middleware. Middleware 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.

Creating an Error Handler

An error handling middleware function has four arguments instead of the usual three: (err, req, res, next). Let's create a basic error handler:

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

In this code, if there's an error, Express will bypass all remaining route handlers and middleware, and call this function. The error object is logged to the console, and the client gets a 'Something broke!' message.

3. Code Examples

Custom 404 Error Page

If a client requests a non-existent route, we can send a custom 404 page.

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

In this code, app.use without a route will match all requests, hence it's placed at the end after all other app.use and routes. If no route matches the client's request, this middleware function will be called, and the client gets a 'Sorry, we cannot find that!' message.

Custom Error Message Based on Error Type

You can also provide custom error responses based on the type of error.

app.use(function (err, req, res, next) {
  if (err instanceof SyntaxError) {
    res.status(400).send('Bad Request: ' + err.message)
  } else {
    next(err)
  }
})

In this code, if the error is a SyntaxError, we send a 'Bad Request' message with the error's message. If it's not a SyntaxError, we call next(err), passing the error to the next error handling middleware.

4. Summary

In this tutorial, we learned how to customize error responses in Express.js. We looked at how to create a basic error handler, how to serve a custom 404 page, and how to provide custom error messages based on the type of error.

The next step is to explore more about Express middleware, and how to use them for tasks such as logging, request validation, and more. For more information on error handling in Express, you can visit the Express.js Error handling documentation.

5. Practice Exercises

  1. Modify the 'Bad Request' error handler to respond with a JSON object instead of a string. The object should have a status property set to 'error', and a message property set to the error's message.
  2. Create a custom error class ValidationError that takes a message and a statusCode property. Modify the 'Bad Request' error handler to handle ValidationError and respond with the status code from the error object.

Solutions and explanations for these exercises can be found on the Express.js Practice Exercises page. As you continue practicing, try to create more custom error classes and handlers for them.

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

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

Date Difference Calculator

Calculate days between two dates.

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