Open In App

Generating Errors using HTTP-errors module in Node.js

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
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.



Similar Reads

What are the differences between HTTP module and Express.js module ?
HTTP and Express both are used in NodeJS for development. In this article, we'll go through HTTP and express modules separately HTTP: It is an in-build module which is pre-installed along with NodeJS. It is used to create server and set up connections. Using this connection, data sending and receiving can be done as long as connections use a hypert
2 min read
Why are HTTP cookies used by Node.js for sending and receiving HTTP cookies?
The HTTP protocol is one of the most important protocols of the Application layer of the OSI model. The main use of this protocol is for sending hypertext information to the client to the server and server to the client to communicate on the World Wide Web. But, the HTTP protocol is a stateless protocol which means that this protocol cannot maintai
5 min read
Will the 'error' event ever be emitted on 'http.IncomingMessage' in a node.js http.request ?
In this article, we will see how to handle the 'error' event that is emitted on 'http.IncomingMessage' in a node.js http.request. In Node.js, the 'http.IncomingMessage' object is used to represent the incoming HTTP request message. This object is a readable stream, and it can emit various events such as 'data', 'end', and 'error'. One of the events
3 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/C++ Code // Node.js program to demonstrate the //
4 min read
Node.js HTTP Module
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. Syntax: const http = require('http');Example 1: In this exam
2 min read
Different types of module used for performing HTTP Request and Response in Node.js
HTTP's requests and responses are the main fundamental block of the World Wide Web. There are many approaches to perform an HTTP request and Response in Node.js. Various open-source libraries are also available for performing any kind of HTTP request and Response. An HTTP request is meant to either retrieve data from a specified URI or to push data
3 min read
How to export promises from one module to another module node.js ?
JavaScript is an asynchronous single-threaded programming language. Asynchronous means multiple processes are handled at the same time. Callback functions vary for the asynchronous nature of the JavaScript language. A callback is a function that is called when a task is completed, thus helps in preventing any kind of blocking and a callback functio
1 min read
Generating Lighthouse Scores using Node.js
Lighthouse is an open-source tool which is used to generate performance of any web page. We can use CLI or chrome extension to generate lighthouse score for a web page but here is the description of how to generate lighthouse score of multiple urls present in a csv file and generate a csv file consisting of scores of Performance, Accessibility, Bes
4 min read
Difference between HTTP/2 and HTTP/1.1
HTTP stands for hypertext transfer protocol & it is used in client-server communication. By using HTTP user sends the request to the server & the server sends the response to the user. There are several stages of development of HTTP but we will focus mainly on HTTP/1.1 which was created in 1997 & the new one is HTTP/2 which was created
3 min read
How to allow classes defined in a module that can be accessible outside of the module ?
The TypeScript scripts written by default are in the global scope which means that all the functions, methods, variables, etc. in one file are accessible in all other TypeScript files. This can lead to conflicts in variables, functions as programmers can edit the function/variable name or value without any realization. Therefore, the concept of mod
3 min read