The node experiences a crash when the redis-server goes offline

Struggling with a persistent issue here. Despite reading numerous documents and posts from others on the same topic, I can't seem to find a solution to prevent this problem. I am intentionally shutting down the redis server to avoid potential disasters in production, but my attempts have been unsuccessful so far. Below is a simplified version of my current code...

var cluster = require('cluster');
var express = require('express');
var http = require('http');
var redis = require('redis');
var redisAdapter = require('socket.io-redis');
var sticky = require('sticky-session');
var port = process.env.PORT || 3333;
var workers = 3;
var app = express();
var server = http.createServer(app);
var io = require('socket.io')(server);

if(!sticky.listen(server, 3333, {workers: workers})) {
    server.once('listening', () => {
        console.log('server started on port ' + port);
        process.on('exit', () => {
            io.emit('error', {errorType: 'SERVER_SHUTDOWN'});
        });
        process.on('uncaughtException', (err) => {
            console.log('uncaught exception occurred');
            console.log(err);
        });
    });
} else {
    addRedisAdapter(io);
    addIOEventHandler(io);
}

function addRedisAdapter(io) {
    var redisUrl = process.env.REDISTOGO_URL || 'redis://127.0.0.1:6379';
    var redisOptions = require('parse-redis-url')(redis).parse(redisUrl);
    var pub = redis.createClient(redisOptions.port, redisOptions.host, { returnBuffers: true});
    var sub = redis.createClient(redisOptions.port, redisOptions.host, {returnBuffers: true});
    io.on('error', (err) => {
        console.log(err);
    });
    io.on('uncaughtException', (err) => {
        console.log(err);
    });
    io.adapter(redisAdapter({pubClient: pub, subClient: sub}));
    console.log('redis adapter started');
}
function addIOEventHandler(io) {
    //all the events for io
}

The sequence starts with initiating the redis-server followed by launching node.js with this server. Afterward, in a terminal window, I execute "redis-cli shutdown" to forcefully bring down the redis server. Immediately after that, the node.js terminal goes into a frenzy, repeatedly displaying the same error message.

events.js:154
  throw er; // Unhandled 'error' event
  ^

Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
    at Object.exports._errnoException (util.js:893:11)
    at exports._exceptionWithHostPort (util.js:916:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1075:14)
redis adapter started with url: redis://127.0.0.1:6379

Despite implementing handlers like process.on('uncaughtException', io.on('uncaughtException', and io.on('error', the server still loops through saying there is an "Unhandled 'error' event". Any assistance would be greatly appreciated as I've exhausted all resources available online without success.

Answer №1

Big thanks to @SadiRubaiyet for guiding me in the right direction. By adding an error event to both pub and sub, I was able to prevent node crashes when redis goes down. Below is the updated code snippet...

var cluster = require('cluster');
var express = require('express');
var http = require('http');
var redis = require('redis');
var redisAdapter = require('socket.io-redis');
var sticky = require('sticky-session');
var port = process.env.PORT || 3333;
var workers = 3;
var app = express();
var server = http.createServer(app);
var io = require('socket.io')(server);

if(!sticky.listen(server, 3333, {workers: workers})) {
    server.once('listening', () => {
        console.log('Server has started on port ' + port);
        process.on('exit', () => {
            io.emit('error', {errorType: 'SERVER_SHUTDOWN'});
        });
        process.on('uncaughtException', (err) => {
            console.log('An uncaught exception occurred');
            console.log(err);
        });
    });
} else {
    addRedisAdapter(io);
    addIOEventHandler(io);
}

function addRedisAdapter(io) {
    var redisUrl = process.env.REDISTOGO_URL || 'redis://127.0.0.1:6379';
    var redisOptions = require('parse-redis-url')(redis).parse(redisUrl);
    var pub = redis.createClient(redisOptions.port, redisOptions.host, { returnBuffers: true});
    var sub = redis.createClient(redisOptions.port, redisOptions.host, {returnBuffers: true});
    io.on('error', (err) => {
        console.log(err);
    });
    io.on('uncaughtException', (err) => {
        console.log(err);
    });
    /*NEW FUNCTIONALITY THAT FIXED THE ISSUE*/
    pub.on('error', (err) => {
        console.log('Error from pub');
        console.log(err);
    });
    sub.on('error', (err) => {
        console.log('Error from sub');
        console.log(err);
    });
    /*END*/
    io.adapter(redisAdapter({pubClient: pub, subClient: sub}));
    console.log('Redis adapter has been initiated');
}
function addIOEventHandler(io) {
    //all the events for io
}

Answer №2

To solve the problem at hand, I successfully tackled it by implementing the following line of code:

 io.of('/').adapter.on('error', function(error){
          console.log('error: ', error);            
       });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When I try to reverse the words in a string, I am not receiving the desired order

Currently delving into TypeScript, I have set myself the task of crafting a function that takes in a string parameter and reverses each word within the string. Here is what I aim to achieve with my output: "This is an example!" ==> "sihT ...

Error Found: Syntax Error - 'if' statement not recognized

if (fname == null || fname == "") { Receiving an error message "uncaught syntax error:unexpected token if in line 13". The error indicates "SyntaxError: missing variable name" when using Javascript lint function validateRegistration() { var emailReg ...

Tips for controlling HTML elements using JavaScript

I'm currently working on implementing a mouse-over scale effect for an HTML image. I chose to use JavaScript for this task because I need the ability to manipulate multiple elements in different ways simply by hovering over one element. Below is the J ...

The instance is referencing "underscore" during render, but it is not defined as a property or method

I have experience as a skilled react developer, but I've taken over a vue.js project from another developer and managed it for quite some time. Regrettably, I haven't put in the effort to learn vue properly. When using lodash, I encountered an u ...

The Cross-Origin Request has been blocked due to the Same Origin Policy prohibiting access to the remote resource. The reason for this is that the CORS preflight response was unsuccessful

SERVERSIDE // Establishing Headers app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE"); res.header("Access-Control-Allow-Headers ...

Group the elements of the second array based on the repeated values of the first array and combine them into a single string

I have a challenge with two arrays and a string shown below var str=offer?; var names = [channelId, channelId, offerType, offerType, Language]; var values =[647, 763, international, programming, English]; Both arrays are the same size. I want to creat ...

Having trouble with cucumberjs in conjunction with selenium, phantomjs, and webdriverio

After installing phantomjs globally using the command npm install -g phantomjs I initiated selenium with the command java -jar selenium-standalone-2.52.0.jar To properly configure the World object for cucumberjs, follow these steps: var options = { ...

The loading on the Express endpoint does not cease, despite configuring the response status (Encountering problems with Multer and Express)

Currently, I am in the process of developing a filter that evaluates a file's signature obtained through a file's buffer provided by Multer. While Multer supplies the MIME type, additional validation methods are required to confirm if the file ma ...

Unable to fetch JSON data from PHP with the help of AJAX

I seem to be encountering an issue with retrieving JSON string data from my PHP script using an AJAX call. Here are the relevant scripts: $.ajax({ type: "POST", async: false, dataType: "json", url: "databas ...

Tips for resolving Electron npm audit fix errors?

This particular inquiry stems from a discussion on Why do renderer fs.existsSync, fs.readfileSync (declared in preload.js) return 'undefined'?, where the issue of method '.toString('base64')' failing due to prototype pollution ...

There seems to be a problem retrieving the JSON file

My JavaScript file is designed to fetch a JSON file and execute a function if successful. If there's an error, it should display an alert window with the message "error". However, despite checking the syntax, I keep receiving an error alert every time ...

Despite using app.use in Express Passport Node.js, the req.user variable is not being properly assigned to res.locals

As a beginner in nodejs, I am embarking on the development of a website that caters to two types of users: regular users and freelancers. Upon user login, res.locals.currentUser is set as req.user using the middleware app.use (which is applied universally ...

"Exploring the process of assigning input data to a different variable within a Vue component

Reviewing the code snippet I currently have: <template> <div> <input v-model.number="money"> <p>{{ money }}</p> </div> </template> <script> name: 'MyComponent', data () { ...

Having trouble with installing an npm package into your system?

I attempted multiple methods to install this package: npm install cloud-print npm install https://github.com/postmen/node-cloud-print.git and so forth... However, each time I encountered the following output: `npm WARN addRemoteGit Error: Command fai ...

Having trouble with adding a class on scroll?

My challenge is to extract the header from this website, by adding an additional class when the user scrolls at a position greater than 0. I thought it would be easy, but Java always presents problems for me. Here’s the code I came up with: <!DOCTY ...

What is the process for executing a Js file on a website?

I am looking to automate some tasks on a website that I do not own. Specifically, I need to automatically fill out a form and perform certain clicking actions. Can JavaScript be used for this purpose? I am unsure how to run a .js file on a site without the ...

JavaScript's multiple inheritance concept

In the realm of JavaScript, there exists a class that seeks to 'inherit' various objects and their methods. var A = function (a,c){}; var N = { properties1: function(){}; }; var M1 = { properties2: function(){}; }; var M2 = { ...

The Holy Alliance of Laravel and Vue

I am facing issues with user authentication using Laravel Sanctum. I have set up everything properly, with Vite and Vue 3 as the frontend. The problem arises when I attempt to login with Laravel's default auth - it works fine. However, when I make a r ...

What is the best way to execute a function that retrieves data from a MySQL query and then sends it back as a result in Express.js?

How can I refactor my code to efficiently call a function that returns the result of a MySQL query and send it back in an Express.js response? I am attempting to streamline my SQL queries by exporting them into individual functions to eliminate duplicatio ...

The functions Show() and Hide() may not work in all scenarios within jQuery

I'm currently developing a website that allows users to participate in quizzes. Each quiz consists of 20 questions divided into three sections: 1 mark for 10 questions, 2 marks for 5 questions, and 4 marks for 5 questions. For each question, there are ...