Skip to content

Commit

Permalink
fix: toJSON recursive error serialization (fix #5848) (#5884)
Browse files Browse the repository at this point in the history
  • Loading branch information
eddienubes authored Jun 16, 2024
1 parent 84a4fdb commit 8d55d6b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/utils/src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export function serializeError(val: any, seen = new WeakMap()): any {
if (typeof val.asymmetricMatch === 'function')
return `${val.toString()} ${format(val.sample)}`
if (typeof val.toJSON === 'function')
return val.toJSON()
return serializeError(val.toJSON(), seen)

if (seen.has(val))
return seen.get(val)
Expand Down
28 changes: 28 additions & 0 deletions test/core/test/serialize.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,4 +168,32 @@ describe('error serialize', () => {
message: 'test',
})
})

it('should serialize when toJSON does not return JSON-compatible object', () => {
class TestClass {}

const error = {
key: 'value',
// Still not serialized, thus second round of serialization is needed
toJSON() {
return {
key: 'value',
obj: {
fn: () => {},
class: TestClass,
},
}
},
}

const serialized = serializeError(error)

expect(serialized).toEqual({
key: 'value',
obj: {
fn: 'Function<fn>',
class: 'Function<TestClass>',
},
})
})
})

0 comments on commit 8d55d6b

Please sign in to comment.