HTTPS module error handling when disconnecting from internet in Node.js
Last Updated :
26 Apr, 2025
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 code example, which makes an HTTPS request to a remote server using the HTTPS module:
Javascript
const https = require( 'https' );
console.log(res.statusCode);
}).on( 'error' , (err) => {
console.error(err);
});
|
If the internet connection is lost or disrupted while the HTTPS request is being made, the following error may be thrown.

Error
This error indicates that the connection to the server was refused, likely due to a problem with the internet connection.
Approach: To handle this error, we can use the error event of the https.ClientRequest object returned by the https.get() function. The error event is emitted when an error occurs while making the request. We can attach a listener function to this event to handle the error.
Example 1: Here is an example of how to retry the HTTPS request using a loop. In this code, the makeRequest() function is defined to make an HTTPS request to the URL https://www.example.com using the https.get() function. If the request is successful, the status code of the response is logged to the console. If the request fails, the error event of the https.ClientRequest object is emitted, and the error is logged to the console. The code then checks the error code of the error object. If the error code is ECONNREFUSED, which indicates that the connection was refused, the code enters a loop that retries the request a maximum of 5 times. The number of retries is tracked using the numRetries variable, and a message is logged to the console indicating the current attempt and the total number of attempts. After the maximum number of retries has been reached, the loop exits, and the request is not retried further. If the error code is not ECONNREFUSED, the request is not retried.
Javascript
const https = require( 'https' );
function makeRequest() {
console.log(res.statusCode);
}).on( 'error' , (err) => {
console.error(err);
if (err.code === 'ECONNREFUSED' ) {
const maxRetries = 5;
let numRetries = 0;
while (numRetries < maxRetries) {
numRetries++;
console.log(`Retrying request...
Attempt ${numRetries} of ${maxRetries}`);
makeRequest();
}
}
});
}
makeRequest();
|
Output: This code will retry the HTTPS request up to 5 times if the error was due to a problem with the internet connection. The output of this code may look something like this:

modified(retry)
Example 2: In this code example, the retry loop is implemented using an if statement that checks if the number of retries is less than the maximum number of retries allowed. If the condition is true, the makeRequest() function is called again with numRetries incremented by 1. This continues until the maximum number of retries is reached, at which point the if statement evaluates to false and the loop is exited. This code will also retry the HTTPS request up to 5 times if the error was due to a problem with the internet connection. The output of this code will be similar to the previous example.
Javascript
const https = require( 'https' );
function makeRequest(numRetries) {
console.log(res.statusCode);
}).on( 'error' , (err) => {
console.error(err);
if (err.code === 'ECONNREFUSED' ) {
const maxRetries = 5;
if (numRetries < maxRetries) {
console.log(`Retrying request...
Attempt ${numRetries + 1} of ${maxRetries}`);
makeRequest(numRetries + 1);
}
}
});
}
makeRequest(0);
|
Output:
Example 3: One approach that is often used to handle errors when making HTTPS requests in Node.js is to use a library such as axios or request-promise. These libraries provide built-in error handling and retry functionality, which can make it easier to implement error handling in your application. For example, using axios, you can make an HTTPS request and handle errors as follows:
In this code, the axios.get() function is used to make an HTTPS request to the URL https://www.example.com. The then() method is used to specify a callback function that is executed if the request is successful, and the catch() method is used to specify a callback function that is executed if the request fails.
If the request is successful, the status code of the response is logged to the console. If the request fails, the error is logged to the console and the error code is checked. If the error code is ECONNREFUSED, which indicates that the connection was refused, the axios.get() function is called again to retry the request. If the request is successful this time, the status code is logged to the console. If the request still fails, the error is logged to the console again.
Javascript
const axios = require( 'axios' );
.then((res) => {
console.log(res.statusCode);
})
. catch ((err) => {
console.error(err);
if (err.code === 'ECONNREFUSED' ) {
.then((res) => {
console.log(res.statusCode);
})
. catch ((err) => {
console.error(err);
});
}
});
|
Output: If the request fails with a connection refused error, the error is logged to the console and the request is retried:

axios handling output
The axios library provides a convenient way to make HTTP requests in Node.js and includes features like automatic retries and error handling. In this code, the catch() method is used to handle errors that may occur while making the request, and the then() method is used to execute a callback function if the request is successful. Using a library such as axios or request-promise can be a more convenient and robust approach to handling errors when making HTTPS requests in Node.js, as it provides built-in error handling and retry functionality.
It is important to note that these examples only handle the error when the internet connection is lost or disrupted. It is also important to handle other types of errors that may occur, such as invalid URLs or server-side errors. Handling errors when working with the HTTPS module in Node.js is important to ensure that the application continues to function properly. By adding error handling logic, such as retrying the request when the error is due to a problem with the internet connection, it is possible to prevent disruptions in the normal flow of the application.
Reference: https://github.com/axios/axios
Similar Reads
Generating Errors using HTTP-errors module in Node.js
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 wit
2 min read
How to Handle MySQL Connection Errors in NodeJS?
Dealing with MySQL connection errors requires you to look at issues related to establishing, maintaining, and closing connections to the MySQL database. This includes initial connection failure, connection drop detection and recovery, and error handling during query execution. Effective error handli
2 min read
Hook error handling doesn't catch errors in ReactJS
In this article, we will see one of the common issues faced by ReactJS developers is the Hook error handling problem. This issue occurs when an error is thrown inside a Hook, but it is not caught and handled properly. As a result, the error goes unaddressed and can cause unexpected behavior in the a
2 min read
How to Handle Lost Connection to Mongodb from Nodejs?
Handling lost connections to MongoDB in a Node.js application is crucial for maintaining application reliability and data integrity. However, network issues, database server crashes, or other unexpected events can cause the connection to be lost. This article will guide you through different approac
3 min read
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 th
4 min read
Explain the concept of Domain in Node.js
Introduction: The Node.js domain module is used to catch outstanding errors. Domains provide a way to handle multiple different input-output operations as a single group. If either the event emitter or the callback is registered in the domain and when an error event or throws an error, the domain ob
6 min read
How to get a dialog box if there is no internet connection using jQuery ?
In this article, we will see how to check the internet connection using jQuery. We will be using navigator.onLine which will return true if an internet connection is available otherwise it will return false. Syntax: navigator.onLine Returns: True: If the internet connection is available.False: If th
2 min read
How can you use error boundaries to handle errors in a React application?
Error boundaries are React components that detect JavaScript errors anywhere in their child component tree, log them, and display a fallback UI rather than the crashed component tree. Error boundaries catch errors in rendering, lifecycle functions, and constructors for the entire tree below them. Ta
6 min read
Explain some Error Handling approaches in Node.js
Node.js is an open-source JavaScript runtime environment. It is often used on the server-side to build API for web and mobile applications. A large number of companies such as Netflix, Paypal, Uber, etc use Node.js. Prerequisites: PromisesAsync Await An error is any problem given out by the program
3 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