From 8618706a4ddf77a39b3c152b7abd941efcdd827e Mon Sep 17 00:00:00 2001 From: normancarcamo Date: Thu, 6 Feb 2020 15:56:48 -0600 Subject: [PATCH] Added is.error method --- src/index.ts | 17 +++++++++++++++++ test/index.test.ts | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/src/index.ts b/src/index.ts index be717d6..6185ccb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -289,6 +289,23 @@ class Is { if (this.function(value)) return 'function'; return 'unknown'; } + + error(value?: any): boolean { + if (Object.prototype.toString.call(value) === '[object Error]') { + return true; + } + + if (value && value.stack && value.message) { + if ( + typeof value.stack === 'string' && + typeof value.message === 'string' + ) { + return true; + } + } + + return false; + } } export default new Is(); diff --git a/test/index.test.ts b/test/index.test.ts index 8238667..24fe0ab 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -996,4 +996,41 @@ describe('is', () => { expect(is.between(true, false, [])).toBe(false); }); }); + + describe('error', () => { + it('should be a function', () => { + expect(is.error).toBeFunction(); + }); + it('should be true when is a valid error', () => { + expect(is.error(new Error('Ouch!'))).toBe(true); + expect(is.error({ stack: 'aa', message: 'sss' })).toBe(true); + }); + it('should be false when is not a valid error', () => { + [ + '1.3d', + 'nw-1', + -1.3, + -0.3, + '1.3', + '0.3', + '43', + '-1', + '-1.3', + '-43', + '65536', + Date.now(), + null, + undefined, + {}, + [], + true, + false, + () => {}, + function() {}, + 65536, + '2010-02-03', + '2010-02-03 12:23:21', + ].forEach(value => expect(is.error(value)).toBe(false)); + }); + }); }); \ No newline at end of file