Customizing Error Responses

Tutorial 3 of 5

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.