Skip to content

Commit 36f9271

Browse files
authoredMay 8, 2024··
fix: simplify error class checking (#53)
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.
1 parent bbaa93a commit 36f9271

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed
 

‎index.js

+1-5
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,6 @@ function isErrorInstance(obj) {
33
return obj instanceof Error || Object.prototype.toString.call(obj) === '[object Error]';
44
}
55

6-
function isErrorClass(obj) {
7-
return obj === Error || (typeof obj === 'function' && obj.name === 'Error');
8-
}
9-
106
function isRegExp(obj) {
117
// eslint-disable-next-line prefer-reflect
128
return Object.prototype.toString.call(obj) === '[object RegExp]';
@@ -50,7 +46,7 @@ function compatibleConstructor(thrown, errorLike) {
5046
if (isErrorInstance(errorLike)) {
5147
// If `errorLike` is an instance of any error we compare their constructors
5248
return thrown.constructor === errorLike.constructor || thrown instanceof errorLike.constructor;
53-
} else if (isErrorClass(Object.getPrototypeOf(errorLike)) || isErrorClass(errorLike)) {
49+
} else if ((typeof errorLike === 'object' || typeof errorLike === 'function') && errorLike.prototype) {
5450
// If `errorLike` is a constructor that inherits from Error, we compare `thrown` to `errorLike` directly
5551
return thrown.constructor === errorLike || thrown instanceof errorLike;
5652
}

‎test/index.js

+11
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,17 @@ describe('checkError', function () {
3131

3232
assert(checkError.compatibleConstructor(errorInstance, anObject) === false);
3333
assert(checkError.compatibleConstructor(errorInstance, aNumber) === false);
34+
35+
function PrototypeError() {}
36+
PrototypeError.prototype = Object.create(Error.prototype);
37+
assert(checkError.compatibleConstructor(new PrototypeError(), PrototypeError) === true);
38+
assert(checkError.compatibleConstructor(new PrototypeError(), Error) === true);
39+
40+
// eslint-disable-next-line func-style
41+
const WeirdNamelessError = function () {};
42+
WeirdNamelessError.prototype = Object.create(Error.prototype);
43+
assert(checkError.compatibleConstructor(new WeirdNamelessError(), WeirdNamelessError) === true);
44+
assert(checkError.compatibleConstructor(new WeirdNamelessError(), Error) === true);
3445
});
3546

3647
it('compatibleMessage', function () {

0 commit comments

Comments
 (0)
Please sign in to comment.