From f884c51deb2113f6ad772d85cce44a366712f8a8 Mon Sep 17 00:00:00 2001 From: Adrien Gibrat Date: Fri, 17 May 2019 15:54:05 +0200 Subject: [PATCH] feat(log): Behave like native Error when using console.log Only CustomError class was behaving different from native Error Add basic unit test to avoid regression fix #30 --- src/custom-error.spec.ts | 3 +++ src/custom-error.ts | 8 ++++++-- src/factory.spec.ts | 5 +++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/custom-error.spec.ts b/src/custom-error.spec.ts index edc5a9d..d0e9c60 100755 --- a/src/custom-error.spec.ts +++ b/src/custom-error.spec.ts @@ -54,3 +54,6 @@ test('Without message', () => name: 'CustomError', message: '', })) + +test('native log behaviour', () => + expect(`${new CustomError('Hello')}`).toMatch('CustomError: Hello')) diff --git a/src/custom-error.ts b/src/custom-error.ts index 0c295ee..c15c4dc 100644 --- a/src/custom-error.ts +++ b/src/custom-error.ts @@ -22,9 +22,13 @@ export class CustomError extends Error { constructor(message?: string) { super(message) - // set error name as constructor name + // set error name as constructor name, make it not enumerable to keep native Error behavior // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new.target#new.target_in_constructors - this.name = new.target.name + // see https://github.com/adriengibrat/ts-custom-error/issues/30 + Object.defineProperty(this, 'name', { + value: new.target.name, + enumerable: false, + }) // fix the extended error prototype chain // because typescript __extends implementation can't // see https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work diff --git a/src/factory.spec.ts b/src/factory.spec.ts index c385136..e59e6ed 100644 --- a/src/factory.spec.ts +++ b/src/factory.spec.ts @@ -85,3 +85,8 @@ test('Factory properties', () => { message: 'foo', }) }) + +test('native log behaviour', () => + expect(`${customErrorFactory(function TestError(this: Props, message) { + this.message = message + })('Hello')}`).toMatch('TestError: Hello'))