Generating Errors using HTTP-errors module in Node.js
Last Updated :
06 Apr, 2023
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
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
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: J
4 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
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
Node.js util.getSystemErrorName() Method The util.getSystemErrorName() method is defined in utilities module of Node.js standard library. It is used to know the type of error that occurs in the program. Generally, this method is used within some other method to know if that method does not give response as expected because some error occur
4 min read
How to Handle Errors for Async Code in Node.js ? Handling errors effectively in asynchronous code is crucial for building robust and reliable Node.js applications. As Node.js operates asynchronously by default, understanding how to manage errors in such an environment can save you from unexpected crashes and ensure a smooth user experience. This a
4 min read
Node.js http.ServerResponse.connection Method The httpServerResponse.connection is an inbuilt application programming interface of class Server Response within http module which is used to get the response socket of this HTTP connection. Syntax: response.connection Parameters: This method does not accept any argument as a parameter. Return Valu
2 min read