How to handle unhandled exceptions in libraries in node.js

I have a node.js application using Express and Redis. My question is: how do I catch and handle a Redis connection error. I have an app.error function in an expression that handles most application errors, but since this error is an error that gets into the redis library, it becomes an uncaught exception, and the whole application is reduced.

Is it possible to simply define the on_error method on my redis client and this will do the trick? If so, maybe some sample code? Should I somehow handle this in the next node.js next tick error? I'm not sure I understand the following statement in a way that is not sure which is the best practice.

In the code below, the catch block never gets caught, even if there is a connection error

try { feedClient = redis.createClient(feedPort, feedHost); } catch (error) { console.log('cannnot start redis' + error); } 

Here is a fuzzy mistake

 node.js:134 throw e; // process.nextTick error, or 'error' event on first tick ^ Error: Redis connection to localhost:6379 failed - ECONNREFUSED, Connection refused at RedisClient.on_error (/node_modules/redis/index.js:136:24) at Socket. (/node_modules/redis/index.js:70:14) at Socket.emit (events.js:64:17) at Array. (net.js:830:27) at EventEmitter._tickCallback (node.js:126:26) 
+6
source share
1 answer

Yes, you need to specify an error handler:

 feedClient = redis.createClient(feedPort, feedHost); feedClient.on("error", function(err) { console.error("Error connecting to redis", err); }); 
+11
source

Source: https://habr.com/ru/post/908645/


All Articles