Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
What is the use of next() function in Express.js ?
Next article icon

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

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Prerequisites

  • Node JS
  • Express JS

Table of Content

  • Role of next(err) in Error Handling Middleware
  • Steps to use next(err) in error handling middleware in 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.

  1. Pass Control to the Next Middleware: When the next(err) is called, the Express knows that an error has occurred, so it skips the control to the next middleware function which handles the error.
  2. Error Propagation: The parameter err consists of the information about the error that has occurred. This parameter is mostly the instance of the "Error" object it can be a custom object also. We can also log the error information, which is sent as a response to the client.
  3. Bypass the Regular Middleware: In the application, when the error has occurred and the next(Err) function is called, the regular middleware functions for the current route are skipped and the control is passed to the next middleware to handle the error.
  4. Error Response: The middleware that is developed to handle these errors can give the correct response to the client. This can include the logging of errors or sending some specific HTTP status codes that give the information about the error.

Syntax:

app.use((err, req, res, next) => {
// Handle the error or log it
console.error(err);
// Pass the error to the next error-handling middleware
next(err);
});

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

1

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

2

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

npm i express

3

Dependencies:

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

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

4

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 GeeksforGeeks     const err = new Error("Failed to fetch data from GeeksforGeeks API");     err.status = 500;     // additional data related to     // GeeksforGeeks to the error object     err.geeksforGeeksData = {         endpoint: "/api/geeks/data",         message: `Check if GeeksforGeeks 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 GeeksforGeeks     res.status(err.status || 500).json({         error: {             message: err.message || "Something went wrong!",             geeksforGeeksData: err.geeksforGeeksData || 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 GeeksforGeeks 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.

Next Article
What is the use of next() function in Express.js ?

G

gauravggeeksforgeeks
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Geeks Premier League
  • Express.js
  • Geeks Premier League 2023

Similar Reads

  • What is the purpose of the compression middleware in Express JS ?
    Middleware in Express JS is like a set of tools or helpers that helps in managing the process when your web server gets a request and sends a response. Mainly it’s work is to make the ExpressJS framework more powerful and flexible. It allows users to insert additional steps or actions in the process
    2 min read
  • What is the purpose of the express-validator middleware in Express JS?
    The express-validator middleware is a powerful tool for validating and sanitizing incoming request data in ExpressJS applications. It helps ensure that user input meets specified criteria, preventing security vulnerabilities and data corruption. With built-in error handling and customizable rules, e
    2 min read
  • What is the use of next() function in Express.js ?
    Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client's different incoming requests. In this article, we will discuss, the use of the next() function in every middleware of the express.js. There ar
    2 min read
  • What is middleware chaining in Express JS, and how is it useful?
    In Express JS there is the process of Middleware chaining by which multiple middleware functions sequentially can be processed and also can be able to modify the incoming requests before they reach the final route handler. In this article, we will see the concept of Middleware Chaining in Express JS
    4 min read
  • What is Middleware in Express.js ?
    Middleware functions have access to the request object and the response object and also the next function in the application request-response lifecycle. Middlewares are used for: Change the request or response object.Execute any program or codeEnd the request-response lifecycleCall the next middlewa
    2 min read
  • What is express-session middleware in Express?
    In the Express web application, the express-session middleware is mainly used for managing the sessions for the user-specific data. In this article, we will see the use of express-session middleware for session management in Express with practical implementation. PrerequisitesNode JSExpress JSTable
    2 min read
  • How To Create Custom Error Handler Middleware in Express?
    In ExpressJS there is a built-in class named CustomError which is basically used to create an error of your choice. in this article, we will see how with the use of this CustomError class we can create a custom error handler middleware in ExpressJS. What is a CustomError Handler?A custom error handl
    5 min read
  • What is The Difference Between Interceptor, Middleware and Filter in Nest.js?
    Nest.js is a popular framework for building server-side applications in Node.js. While working with Nest.js, we'll often come across terms like Interceptor, Middleware, and Filter. These are important concepts that help in managing requests, responses, and errors in your application. What is Middlew
    5 min read
  • How to resolve req.body is empty in posts error in Express?
    In Express the req.body is empty error poses a critical challenge in web development, particularly in the context of processing POST requests on the server side. This issue arises when the server encounters difficulties parsing the request body, resulting in an empty or undefined req.body object. De
    4 min read
  • Express Error Handling - Middleware for Production and Development
    Error handling is the process of detecting and responding to errors that occur during the execution of a program or application. In the context of web applications, error handling typically involves detecting errors that occur during the handling of HTTP requests and responding appropriately to thos
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences