Handling Asynchronous Errors in Express with "express-async-errors"

  • by Haozheng Li
  • 0 likes

Handling Asynchronous Errors in Express with express-async-errors

When working with Express.js, handling errors in asynchronous functions can be a bit tricky. Express's default error handling mechanism does not catch exceptions thrown in asynchronous code (e.g., using async/await). This is where the express-async-errors library comes to the rescue. It simplifies error handling in asynchronous routes by allowing you to leverage the global error-handling middleware without needing to manually add try-catch blocks in every async function.

Installation

You can install the express-async-errors library using npm:

npm install express-async-errors

How to Use

To use this library, simply import it at the top of your main file (e.g., server.js) before declaring your routes. This library automatically modifies Express's behavior to catch asynchronous errors and pass them to the error-handling middleware.

Example Code

Without express-async-errors

Without express-async-errors, you need to manually handle errors in each asynchronous function using try-catch blocks:

import express from "express";
import mongoose from "mongoose";
import dotenv from "dotenv";

dotenv.config();

const app = express();

app.use(express.json());

app.get("/", (req, res) => {
  res.send("Hello, SSO!");
});

app.get("/async-route", async (req, res, next) => {
  try {
    const data = await someAsyncFunction();
    res.send(data);
  } catch (err) {
    next(err); // Pass the error to the error-handling middleware
  }
});

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

const port = process.env.PORT || 5100;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

With express-async-errors

When using express-async-errors, you no longer need to manually add try-catch blocks in each async function. The library automatically catches these errors and passes them to the error-handling middleware:

import express from "express";
import mongoose from "mongoose";
import dotenv from "dotenv";
import "express-async-errors"; // Import the express-async-errors library

dotenv.config();

const app = express();

app.use(express.json());

app.get("/", (req, res) => {
  res.send("Hello, SSO!");
});

app.get("/async-route", async (req, res) => {
  const data = await someAsyncFunction();
  res.send(data);
});

// Global error-handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send("Something broke!");
});

const port = process.env.PORT || 5100;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

By incorporating express-async-errors, you can simplify your code and make it cleaner and easier to maintain. It allows you to focus on the core functionality of your application rather than error handling in every async route.

Exploring the Benefits of Using Vite with React: A Comparison with Create React App

Comments

0 Comments