From daa8d9a8806801723c74ade657edcc15f4d464cb Mon Sep 17 00:00:00 2001 From: lucasfcosta Date: Sun, 5 Jun 2016 20:51:58 -0300 Subject: [PATCH] fix: getConstructor name working with PoorlyConstructedErrors --- index.js | 6 ++++-- test/index.js | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 463345b..70f5661 100644 --- a/index.js +++ b/index.js @@ -129,8 +129,10 @@ function getConstructorName(errorLike) { if (errorLike instanceof Error) { constructorName = getFunctionName(errorLike.constructor); } else if (typeof errorLike === 'function') { - // if `err` is not an instance of Error it is an error constructor itself - constructorName = getFunctionName(errorLike); + // If `err` is not an instance of Error it is an error constructor itself or another function. + // If we've got a common function we get its name, otherwise we may need to create a new instance + // of the error just in case it's a poorly-constructed error. Please see chaijs/chai/issues/45 to know more. + constructorName = getFunctionName(errorLike) || getFunctionName(new errorLike()); // eslint-disable-line new-cap } return constructorName; diff --git a/test/index.js b/test/index.js index 7f0fcaa..bc9aec2 100644 --- a/test/index.js +++ b/test/index.js @@ -85,8 +85,22 @@ describe('checkError', function () { return 1; } + var anonymousFunc = function () { // eslint-disable-line func-style + return 2; + }; + + // See chaijs/chai/issues/45: some poorly-constructed custom errors don't have useful names + // on either their constructor or their constructor prototype, but instead + // only set the name inside the constructor itself. + var PoorlyConstructedError = function () { // eslint-disable-line func-style + this.name = 'PoorlyConstructedError'; // eslint-disable-line no-invalid-this + }; + PoorlyConstructedError.prototype = Object.create(Error.prototype); + assert(checkError.getConstructorName(correctName) === 'correctName'); assert(checkError.getConstructorName(withoutComments) === 'withoutComments'); + assert(checkError.getConstructorName(anonymousFunc) === ''); + assert(checkError.getConstructorName(PoorlyConstructedError) === 'PoorlyConstructedError'); }); it('getMessage', function () {