Skip to content

Commit

Permalink
fix: handle circular refs in errors
Browse files Browse the repository at this point in the history
Fixes chaijs/chai#1645

We already handle circular references in objects, but do not do the same
for `Error` objects. This change adds the same `seen` logic to error
inspection as we have in object inspection.
  • Loading branch information
43081j committed Oct 7, 2024
1 parent d8f129d commit 3397d91
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const errorKeys = [
'columnNumber',
'number',
'description',
'cause',
]

export default function inspectObject(error: Error, options: Options) {
Expand All @@ -26,6 +27,11 @@ export default function inspectObject(error: Error, options: Options) {
}
message = message ? `: ${message}` : ''
options.truncate -= message.length + 5
options.seen = options.seen || []
if (options.seen.indexOf(error) >= 0) {
return '[Circular]'
}
options.seen.push(error)
const propertyContents = inspectList(
properties.map(key => [key, error[key as keyof typeof error]]),
options,
Expand Down
14 changes: 14 additions & 0 deletions test/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,19 @@ describe('errors', () => {
err.message = { code: 404 }
expect(inspect(err)).to.equal('Error { message: { code: 404 } }')
})

it('detects circular references', () => {
const err = new Error('message')
err.fluff = err
expect(inspect(err)).to.equal('Error: message { fluff: [Circular] }')
})
})

describe('ignores built in properties', () => {
it('does not add property to output', () => {
const err = new Error('message')
err.cause = new Error('i caused you')
expect(inspect(err)).to.equal('Error: message')
})
})
})

0 comments on commit 3397d91

Please sign in to comment.