The domain
built-in module will be deprecated:
Stability: 0 - Deprecated
This module is pending deprecation. Once a replacement API has been finalized, this module will be fully deprecated. Most end users should not have cause to use this module. Users who absolutely must have the functionality that domains provide may rely on it for the time being but should expect to have to migrate to a different solution in the future.
According to this, they don't really recommend a solution currently. But how to implement a functionality which is similar to the below one:
var d = require('domain').create();
d.on('error', function(err) {
console.log(err);
});
d.run(function() {
setTimeout(function () {
throw new Error("Something went really wrong in async code.");
}, 1000);
});
So, this handles the errors thrown from async stuff, but the domain
module is deprecated.
How to migrate this code to something better?
My use-case is that I'm writing a library which accepts a function as input and it runs the function and displays the result (actually, you can think at it as unit-testing library):
myLib.it("should do something", function (done) {
setTimeout(function () {
// Some async code
// ...
// But here an error is thrown
throw new Error("dummy");
}, 1000);
});
Obviously, I don't want to crash the process in this case but I do want to show a nice error (so basically catching the error in this function).
Currently in the library I do:
var err = null;
try {
fn(callback);
} catch (e) {
err = e;
}
console.log(err || "Everything went correctly");