Skip to content

Commit

Permalink
fix: simplify error class checking (#53)
Browse files Browse the repository at this point in the history
Previously, we were unnecessarily trying to determine if the passed
object was in fact a class which extends `Error`.

We don't actually care about this, really. We just want to know if the
`thrown` is an instance of the thing you passed.

Due to this, we can simplify by simply checking that the `errorLike` is
something with a `prototype` and assert that the `thrown` is an instance
of it.
  • Loading branch information
43081j committed May 8, 2024
1 parent bbaa93a commit 36f9271
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
6 changes: 1 addition & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@ function isErrorInstance(obj) {
return obj instanceof Error || Object.prototype.toString.call(obj) === '[object Error]';
}

function isErrorClass(obj) {
return obj === Error || (typeof obj === 'function' && obj.name === 'Error');
}

function isRegExp(obj) {
// eslint-disable-next-line prefer-reflect
return Object.prototype.toString.call(obj) === '[object RegExp]';
Expand Down Expand Up @@ -50,7 +46,7 @@ function compatibleConstructor(thrown, errorLike) {
if (isErrorInstance(errorLike)) {
// If `errorLike` is an instance of any error we compare their constructors
return thrown.constructor === errorLike.constructor || thrown instanceof errorLike.constructor;
} else if (isErrorClass(Object.getPrototypeOf(errorLike)) || isErrorClass(errorLike)) {
} else if ((typeof errorLike === 'object' || typeof errorLike === 'function') && errorLike.prototype) {
// If `errorLike` is a constructor that inherits from Error, we compare `thrown` to `errorLike` directly
return thrown.constructor === errorLike || thrown instanceof errorLike;
}
Expand Down
11 changes: 11 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@ describe('checkError', function () {

assert(checkError.compatibleConstructor(errorInstance, anObject) === false);
assert(checkError.compatibleConstructor(errorInstance, aNumber) === false);

function PrototypeError() {}
PrototypeError.prototype = Object.create(Error.prototype);
assert(checkError.compatibleConstructor(new PrototypeError(), PrototypeError) === true);
assert(checkError.compatibleConstructor(new PrototypeError(), Error) === true);

// eslint-disable-next-line func-style
const WeirdNamelessError = function () {};
WeirdNamelessError.prototype = Object.create(Error.prototype);
assert(checkError.compatibleConstructor(new WeirdNamelessError(), WeirdNamelessError) === true);
assert(checkError.compatibleConstructor(new WeirdNamelessError(), Error) === true);
});

it('compatibleMessage', function () {
Expand Down

0 comments on commit 36f9271

Please sign in to comment.