Steps to use next(err) in error handling middleware in Express.js

Step 1: In the first step, we will create the new folder as next-error by using the below command in the VSCode terminal.

mkdir next-error
cd next-error

Step 2: After creating the folder, initialize the NPM using the below command. Using this the package.json file will be created.

npm init -y

Step 3: Now, we will install the express dependency for our project using the below command.

npm i express

Dependencies:

"dependencies": {
"express": "^4.18.2",
}

Step 4: Now create the below Project Structure of our project which includes the file as app.js.

Step 5: Use the below app.js code to use the next(err) in error handling middleware in Express.js.

Javascript




// app.js
const express = require("express");
const app = express();
 
app.use((req, res, next) => {
    // simulating an error while fetching data from w3wiki
    const err = new Error("Failed to fetch data from w3wiki API");
    err.status = 500;
    // additional data related to
    // w3wiki to the error object
    err.w3wikiData = {
        endpoint: "/api/geeks/data",
        message: `Check if w3wiki API is
      accessible and the data format is correct.`,
    };
    // passing the error to the next middleware
    next(err);
});
 
// error handling middleware
app.use((err, req, res, next) => {
    // logging the error to the console
    console.error(err);
    // sending a user-friendly error
    // response with additional data related to w3wiki
    res.status(err.status || 500).json({
        error: {
            message: err.message || "Something went wrong!",
            w3wikiData: err.w3wikiData || null,
        },
    });
});
 
// starting the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});


To run the application, we need to start the server by using the below command.

node app.js

Output:

Explanation:

  • In the above example, we are showing the error message that there is a failure in fetching data from the w3wiki API.
  • The error is been passed to an error-handling middleware, where we are displaying the error in JSON response.
  • Along with this, there is more data provided like endpoint and helpful message that includes more proper error response.


What is the role of next(err) in error handling middleware in Express JS?

Express is the most popular framework for Node.js which is used to build web-based applications and APIs. In application development, error handling is one of the important concepts that provides the aspect to handle the errors that occur in the middleware. The middleware functions have access to the request object, the response object, and the next middleware function which is defined as next.

In this article, we will see the concept of next(err) for error handling in Express. We will see its Syntax and practical example with output.

Similar Reads

Prerequisites

Node JS Express JS...

Role of next(err) in Error Handling Middleware:

In Express.js the next function is the callback function which is mainly used to pass the control to the next middleware for performing certain tasks. If we use the next function along with the error parameter as (err) then it handles the error which occurs during the processing of the request and passes the control to the next middleware function....

Steps to use next(err) in error handling middleware in Express.js

Step 1: In the first step, we will create the new folder as next-error by using the below command in the VSCode terminal....

Contact Us