Skip to content

Commit

Permalink
feat(log): Behave like native Error when using console.log
Browse files Browse the repository at this point in the history
Only CustomError class was behaving different from native Error

Add basic unit test to avoid regression

fix #30
  • Loading branch information
Adrien Gibrat committed May 17, 2019
1 parent 23624bd commit f884c51
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
3 changes: 3 additions & 0 deletions src/custom-error.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,6 @@ test('Without message', () =>
name: 'CustomError',
message: '',
}))

test('native log behaviour', () =>
expect(`${new CustomError('Hello')}`).toMatch('CustomError: Hello'))
8 changes: 6 additions & 2 deletions src/custom-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions src/factory.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'))

0 comments on commit f884c51

Please sign in to comment.