How to handle errors in a node with a domain?

I use a third-party library. Used by node domain for error handling. If the callback function passed to this third-party library has any error, it ultimately calls the callback several times.

Code example:

 var startFunction = function (callback) { //Call thirdParty function and wait for response thirdPartyFunction(function (error, data) { console.log("Called with"); console.log(arguments); //Assume there is an error in my callback function setTimeout(function () { dd callback.apply(null); }, 2000); }); } //ThirdParty function don't modify anything here var thirdPartyFunction = function (callback) { var Domain = require("domain"); var d = require('domain').create(); d.on('error', function (er) { console.log("hi"); callback.apply(null, er); }); d.run(function () { setTimeout(function () { callback.apply(null, [null, "Hello"]); }, 1000); }); }; startFunction(function () { console.log("Got response") }); 

We reported this error to a third-party library, and they changed the source code. For instance:

 d.on('error', function (er) { if (isCalled == false) { isCalled = true; } else { return; } console.log("hi"); callback.apply(null, er); }); 

Now the problem of the function called repeatedly is solved. But the final callback will never be called.

How to handle this node behavior?

If the third-party version of lib changes the code to, this will lead to a crash of the application. Putting a wrapper domain also doesn't help.

 d.on('error', function (er) { if (isCalled == false) { isCalled = true; } else { throw new Error("Getting called"); return; } console.log("hi"); callback.apply(null, er); }); 

What is the best way to pass such cases to node?

+4
source share
1 answer

You can connect your own domain listener to your callback function, for example:

  var startFunction = function (callback) { //Call thirdParty function and wait for response thirdPartyFunction(function (error, data) { var d1 = require('domain').create(); d1.on('error', function(er){ console.log("bye"); callback.apply(null, er); }); d1.run(function () { console.log("Called with"); console.log(arguments); //Assume there is an error in my callback function setTimeout(function () { dd callback.apply(null); }, 2000); }); }) } 

Thus, if there is an error, it will be caught by your handler, and the error will be sent back to the main level and will not end up in an infinite loop.

+1
source

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


All Articles