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:
How to Handle Syntax Errors in Node.js ?
Next article icon

Generating Errors using HTTP-errors module in Node.js

Last Updated : 06 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

HTTP-errors module is used for generating errors for Node.js applications. It is very easy to use. We can use it with the express, Koa, etc. applications. We will implement this module in an express application.

Installation and Setup: First, initialize the application with the package.json file with the following command: 

npm init

Then, install the module by the following command:

npm install http-errors --save

Also, we are using an express application, therefore, install the express module by the following command: 

npm install express --save

Now, create a file and name it app.js. You can name your file whatever you want.

For importing the modules in your application, write the following code in your app.js file:

javascript




const createError = require('http-errors');
const express = require('express');
const app = express();
 
 

Implementation: Here, comes the main part of our application. For using this module, write the following code in your app.js file:

javascript




// Node program to demonstrate the
const createError = require('http-errors');
const express = require('express');
const app = express();
 
app.use((req, res, next) => {
    if (!req.user) return next(
        createError(401, 'Login Required!!'));
    next();
});
 
app.listen(8080, (err) => {
    if (err) console.log(err);
    console.log(
        `Server Running at http://localhost:8080`);
});
 
 

Here, we are importing the http-errors module and storing it in a variable named as createError. Next, in app.use(), if the user is not authenticated, then our application will create a 401 error saying Login Required!!. The createError is used for generating errors in an application.

To run the code, run the following command in the terminal:

node app.js

and navigate to http://localhost:8080. The output for the above code will be:

List of all Status Codes with their Error Message: 

Status Code    Error Message  400    BadRequest 401    Unauthorized 402    PaymentRequired 403    Forbidden 404    NotFound 405    MethodNotAllowed 406    NotAcceptable 407    ProxyAuthenticationRequired 408    RequestTimeout 409    Conflict 410    Gone 411    LengthRequired 412    PreconditionFailed 413    PayloadTooLarge 414    URITooLong 415    UnsupportedMediaType 416    RangeNotSatisfiable 417    ExpectationFailed 418    ImATeapot 421    MisdirectedRequest 422    UnprocessableEntity 423    Locked 424    FailedDependency 425    UnorderedCollection 426    UpgradeRequired 428    PreconditionRequired 429    TooManyRequests 431    RequestHeaderFieldsTooLarge 451    UnavailableForLegalReasons 500    InternalServerError 501    NotImplemented 502    BadGateway 503    ServiceUnavailable 504    GatewayTimeout 505    HTTPVersionNotSupported 506    VariantAlsoNegotiates 507    InsufficientStorage 508    LoopDetected 509    BandwidthLimitExceeded 510    NotExtended 511    NetworkAuthenticationRequired

Conclusion: The HTTP-errors module is very useful for developers for the quick generation of errors in their messages. In this article, we learned about the HTTP-errors module for Node.js. We have also seen its installation and Implementation.



Next Article
How to Handle Syntax Errors in Node.js ?
author
pranjal_srivastava
Improve
Article Tags :
  • Node.js
  • Web Technologies
  • Node.js-Misc

Similar Reads

  • HTTPS module error handling when disconnecting from internet in Node.js
    When working with the HTTPS module in Node.js, it is possible to encounter an error when the internet connection is lost or disrupted while the HTTPS request is being made. This can cause the request to fail and throw an error, disrupting the normal flow of the application. Consider the following co
    6 min read
  • Basic Authentication in Node.js using HTTP Header
    Basic Authentication is a simple authentication method where the client sends a username and password encoded in base64 format in the HTTP request header.The basic authentication in the Node.js application can be done with the help express.js framework. Express.js framework is mainly used in Node.js
    3 min read
  • How to Handle Errors in Node.js ?
    Node.js is a JavaScript extension used for server-side scripting. Error handling is a mandatory step in application development. A Node.js developer may work with both synchronous and asynchronous functions simultaneously. Handling errors in asynchronous functions is important because their behavior
    4 min read
  • How to Handle Syntax Errors in Node.js ?
    If there is a syntax error while working with Node.js it occurs when the code you have written violates the rules of the programming language you are using. In the case of Node.js, a syntax error might occur if you have mistyped a keyword, or if you have forgotten to close a parenthesis or curly bra
    4 min read
  • Node.js HTTP Module Complete Reference
    To make HTTP requests in Node.js, there is a built-in module HTTP in Node.js to transfer data over the HTTP. To use the HTTP server in the node, we need to require the HTTP module. The HTTP module creates an HTTP server that listens to server ports and gives a response back to the client. Example: C
    4 min read
  • How to check user authentication in GET method using Node.js ?
    There are so many authentication methods like web token authentication, cookies based authentication, and many more. In this article, we will discuss one of the simplest authentication methods using express.js during handling clients get a request in node.js with the help of the HTTP headers.  Appro
    3 min read
  • Node.js http.ClientRequest.abort() Method
    The http.ClientRequest.abort() is an inbuilt application programming interface of class Client Request within http module which is used to abort the client request. Syntax: ClientRequest.abort() Parameters: This method does not accept any argument as a parameter. Return Value: This method does not r
    2 min read
  • How to Handle Errors in MongoDB Operations using NodeJS?
    Handling errors in MongoDB operations is important for maintaining the stability and reliability of our Node.js application. Whether we're working with CRUD operations, establishing database connections, or executing complex queries, unexpected errors can arise. Without proper error handling, these
    8 min read
  • Implementing Csurf Middleware in Node.js
    Csurf middleware in Node.js prevents the Cross-Site Request Forgery(CSRF) attack on an application. By using this module, when a browser renders up a page from the server, it sends a randomly generated string as a CSRF token. Therefore, when the POST request is performed, it will send the random CSR
    4 min read
  • Explain Error Handling in Express.js Using An Example
    Error Handling is one of the most important parts of any web application development process. It ensures that when something goes wrong in your application, the error is caught, processed, and appropriately communicated to the user without causing the app to crash. In Express.js error handling, requ
    9 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