Skip to content

Commit

Permalink
🐛[jsonStringify] do not crash on serialization error (#242)
Browse files Browse the repository at this point in the history
fixes #236
  • Loading branch information
bcaudan authored Jan 24, 2020
1 parent cab0b40 commit e2ead99
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
6 changes: 5 additions & 1 deletion packages/core/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,11 @@ export function jsonStringify(
}
}

let result: string
try {
return JSON.stringify(value, replacer, space)
result = JSON.stringify(value, undefined, space)
} catch {
result = '<error: unable to serialize object>'
} finally {
if (originalToJSON[0]) {
;(value as ObjectWithToJSON).toJSON = originalToJSON[1]
Expand All @@ -160,6 +163,7 @@ export function jsonStringify(
;(prototype as ObjectWithToJSON).toJSON = originalProtoToJSON[1]
}
}
return result
}

function hasToJSON(value: unknown): value is ObjectWithToJSON {
Expand Down
7 changes: 7 additions & 0 deletions packages/core/test/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,13 @@ describe('utils', () => {
expect(jsonStringify(1)).toEqual('1')
expect(jsonStringify(true)).toEqual('true')
})

it('should not crash on serialization error', () => {
const circularReference: any = { otherData: 123 }
;(circularReference as any).myself = circularReference

expect(jsonStringify(circularReference)).toEqual('<error: unable to serialize object>')
})
})

it('should perform a draw', () => {
Expand Down

0 comments on commit e2ead99

Please sign in to comment.