From 36f9271a23f11ab99301a9c0a39f342767267c8d Mon Sep 17 00:00:00 2001 From: James Garbutt <43081j@users.noreply.github.com> Date: Wed, 8 May 2024 21:48:33 +0100 Subject: [PATCH] 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. --- index.js | 6 +----- test/index.js | 11 +++++++++++ 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index ca950fd..872a7b6 100644 --- a/index.js +++ b/index.js @@ -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]'; @@ -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; } diff --git a/test/index.js b/test/index.js index 3b9cc87..1469e3c 100644 --- a/test/index.js +++ b/test/index.js @@ -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 () {