Background:
I have an npm module that I have common error handling code in, including a custom error:
function CustomError () { /* ... */ }
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.constructor = CustomError;
module.exports = CustomError;
I have some other modules (let's call them 'module-a' and 'module-b') which both depend on the error handling module.
I also have some code with uses Bluebirds "filtered catch" functionality:
doSomething
.catch(CustomError, () => { /* ... */ });
The issue:
After some debugging I've discovered (somewhat obviously in hindsight) that errors created in 'module-a' are not instances of errors created by 'module-b'. This is because both modules have their own copy of the JS file containing the CustomError
constructor, which are both run independently.
I would rather not have to resort to my current solution, which is basically:
CustomError.isCustomError = e => e.constructor.toString() === CustomError.toString();
and then:
doSomething
.then(CustomError.isCustomError, () => { /* ... */ });
This is clearly flimsy, and will fall apart if the versions fall out of sync.
So...
Is there some way to ensure that 'module-a' and 'module-b' both use the same instance of the constructor? Or another, less fragile solution.