I am trying to implement a module for custom errors.
It should be possible to instantiate an individual error within the require-statement of the app using this module:
var MyCustomError = require('custom-error')('MyCustomError');
This is the module:
'use strict';
var _CACHE = {};
function initError(name) {
function CustomError(message) {
this.name = name;
this.message = message;
}
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.constructor = CustomError;
_CACHE[name] = CustomError;
}
function createCustomError(name) {
if (!_CACHE[name]) {
initError(name);
}
return _CACHE[name];
}
module.exports = createCustomError;
The require-one-liner above is working so far.
Now, in my service, I want to catch this error explicitly:
var MyCustomError = require('custom-error')('MyCustomError')
// ...
return fooService.bar()
.catch(MyCustomError, function (error) {
logger.warn(error);
throw error;
})
If I reject the promise of fooService.bar in my test by throwing a MyCustomError this is working great.
BUT, this only works because my test and the service are using the same instance of MyCustomError.
For instance, if I remove the the caching-mechanism in my custom-error-module, the catch won't get reached/executed anymore, because bluebird does not understand that the two Errors are of the same type:
function createCustomError(name) {
//if (!_CACHE[name]) {
initError(name);
//}
return _CACHE[name];
}
The specific code of bluebird's handling is located in the catch_filter.js, you can have a look right here.
Though the approach does work within my app, this will sooner lead to problems once multiple modules are using the custom-error-module and the sharing of the same instances is not given any longer.
How can I get this concept up and running by not comparing the instances, but the error type itself?
Cheers,
Christopher