feat(minErr): allow specifying ErrorConstructor in minErr constructor

In some cases, the type of Error thrown by minErr is meaningful, such as in $q where a TypeError
is sometimes required. This fix allows providing an error constructor as the second argument to
minErr, which will be used to construct the error that gets returned by the factory function.
This commit is contained in:
Jeff Cross
2014-08-21 12:23:24 -07:00
parent 23da614043
commit a6bd4bc866
3 changed files with 19 additions and 3 deletions

View File

@@ -4,6 +4,12 @@
var isFunction = function isFunction(value){return typeof value == 'function';};
var isPromiseLike = function isPromiseLike(obj) {return obj && isFunction(obj.then);};
var isObject = function isObject(value){return value != null && typeof value === 'object';};
var minErr = function minErr (module, constructor) {
return function (){
var ErrorConstructor = constructor || Error;
throw new ErrorConstructor(module + arguments[0] + arguments[1]);
};
};
var $q = qFactory(process.nextTick, function noopExceptionHandler() {});

View File

@@ -25,10 +25,13 @@
* should all be static strings, not variables or general expressions.
*
* @param {string} module The namespace to use for the new minErr instance.
* @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
* error from returned function, for cases when a particular type of error is useful.
* @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
*/
function minErr(module) {
function minErr(module, ErrorConstructor) {
ErrorConstructor = ErrorConstructor || Error;
return function () {
var code = arguments[0],
prefix = '[' + (module ? module + ':' : '') + code + '] ',
@@ -69,7 +72,6 @@ function minErr(module) {
message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' +
encodeURIComponent(stringify(arguments[i]));
}
return new Error(message);
return new ErrorConstructor(message);
};
}

View File

@@ -82,4 +82,12 @@ describe('minErr', function () {
expect(myError.message).toMatch(/^\[26\] This is a Foo/);
expect(myNamespacedError.message).toMatch(/^\[test:26\] That is a Bar/);
});
it('should accept an optional 2nd argument to construct custom errors', function() {
var normalMinErr = minErr('normal');
expect(normalMinErr('acode', 'aproblem') instanceof TypeError).toBe(false);
var typeMinErr = minErr('type', TypeError);
expect(typeMinErr('acode', 'aproblem') instanceof TypeError).toBe(true);
});
});