Express-Async-Errors Node JS Example

Express-Async-Errors installation and usage example in a node js project.

Share it on:

Express-Async-Errors Node JS Example

In this tutorial, I'm going to show how to use the Express-Async-Errors package in your applications and how to create errors middleware to catch errors.

Sound good? Let's get started.

What is Express-Async-Errors

Express-Async-Errors library is an amazing way to catch errors at runtime without using try/catch blocks in your async functions.

Install Express-Async-Errors library

Open the terminal and navigate to your project directory, then run the following command:

devsdash.com logo

Code Copied!

npm install express-async-errors --save

Express-Async-Errors usage example

If you import it now in your project, nothing will happen because we need to create an error middleware first.

Create the error middleware

When an error occur it will be sent to this middleware so you can do amazing things like:

Now let's implement the error middleware.

Create a error.js file in your project with the following code:

devsdash.com logo

Code Copied!

module.exports = function (err, req, res, next) {
        
  //respond with a 500 server error
        
  res.status(500).send("This is a server error by express-async-erros");
        
};

Express-Async-Errors setup

Now we are ready to use the express-async-errors library in our project.

  1. Import the library. You have to import the library before creating any routes.

  2. Import the error middleware. The library will pass the request to the error middleware if any error ocuurs.

  3. Create your routes. All the async functions inside these routes will be patched with try/catch under the hood.

  4. Use The error middleware. Handle errors that occurs inside your Async functions

devsdash.com logo

Code Copied!

require("express-async-errors");
const express = require("express");
const error = require("./error.js");

const app = express();

app.get("/", async (req, res) => {
  throw new Error("error");
});

app.use(error);

app.listen(3000);

When you run the code above, express-async-errors will catch the error and send it to the error middleware resulting in the following:

In This tutorial

  • Introduction