Skip to content

Commit

Permalink
fix: getConstructor name working with PoorlyConstructedErrors
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasfcosta committed Jun 6, 2016
1 parent 3919a90 commit daa8d9a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
6 changes: 4 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
14 changes: 14 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand Down

0 comments on commit daa8d9a

Please sign in to comment.