Open In App

HTTPS module error handling when disconnecting from internet in Node.js

Last Updated : 02 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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');
https.get('https://www.example.com', (res) => {
    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() {
    https.get('https://www.example.com', (res) => {
        console.log(res.statusCode);
    }).on('error', (err) => {
        console.error(err);
        // Retry the request if the error was due 
        //to a problem with the internet connection
        if (err.code === 'ECONNREFUSED') {
            // Set a maximum number of retries
            const maxRetries = 5;
            let numRetries = 0;
            // Retry the request in a loop
            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) {
    https.get('https://www.example.com', (res) => {
        console.log(res.statusCode);
    }).on('error', (err) => {
        console.error(err);
        // Retry the request if the error was due to 
        //a problem with the internet connection
        if (err.code === 'ECONNREFUSED') {
            // Set a maximum number of retries
            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);
        // Retry the request if the error was due to 
        //a problem with the internet connection
        if (err.code === 'ECONNREFUSED') {
            axios.get('https://www.example.com')
                .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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads