Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: simplify error class checking #53

Merged
merged 1 commit into from
May 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading