Best Practices for Error Handling in Express

Tutorial 5 of 5

Best Practices for Error Handling in Express

1. Introduction

This tutorial aims to provide learners with a comprehensive understanding of the best practices for handling errors in Express.js. By the end of this lesson, you'll know how to use various error handling techniques to build robust and stable Express applications.

No specific prerequisites are required, but a basic understanding of JavaScript and Express.js would be beneficial.

2. Step-by-Step Guide

Express.js uses middleware to handle errors. This provides a centralized error handling system for your application. Here's how to go about it:

Define Error-handling Middleware Functions

Error-handling middleware always takes four arguments:

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

In this function, err contains the error object. The req and res objects represent the request and the response, respectively. next is a callback function that you can call to pass control to the next error-handling middleware.

Catching Errors

Always make sure to catch errors in your promise chains and async functions. Here's how you can do this:

app.get('/', function (req, res, next) {
  Promise.resolve().then(function () {
    throw new Error('BROKEN') 
  }).catch(next) 
})

In the above code, the error BROKEN is passed to the next middleware function by calling next with the error.

3. Code Examples

Example 1: Basic Error Handling

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

Here, app.use defines an error-handling middleware. When an error is thrown, it's logged to the console, and the user receives a 500 error with the message 'Something broke!'.

Example 2: Catching Errors in Promises

app.get('/', function (req, res, next) {
  Promise.resolve().then(function () {
    throw new Error('BROKEN') 
  }).catch(next) 
})

In this example, the promise chain throws an error BROKEN. The catch statement passes the error to the next middleware function.

4. Summary

In this tutorial, we learned how to handle errors in Express.js. We discussed how to define error-handling middleware functions and how to catch errors in promise chains and async functions.

To enhance your knowledge, you can explore more about the Express.js documentation.

5. Practice Exercises

Exercise 1: Create a new Express.js application and add basic error handling.

Solution:

const express = require('express')
const app = express()

app.get('/', function (req, res) {
  throw new Error('BROKEN') 
})

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

app.listen(3000)

Exercise 2: Modify the previous exercise's application to use promise chains for error handling.

Solution:

const express = require('express')
const app = express()

app.get('/', function (req, res, next) {
  Promise.resolve().then(function () {
    throw new Error('BROKEN') 
  }).catch(next) 
})

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

app.listen(3000)

In the above code, we are using promise chain for error handling. If any error occurs in our Promise, it is caught in the catch block and passed to the next middleware function for error handling.

Remember, practice is the key to mastering any topic. Happy coding!