Skip to content

Commit

Permalink
fix: handle circular refs in errors (#82)
Browse files Browse the repository at this point in the history
* fix: handle circular refs in errors

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 authored Oct 7, 2024
1 parent d8f129d commit 983691f
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
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.includes(error)) {
return '[Circular]'
}
options.seen.push(error)
const propertyContents = inspectList(
properties.map(key => [key, error[key as keyof typeof error]]),
options,
Expand Down
2 changes: 1 addition & 1 deletion src/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export default function inspectObject(object: object, options: Options): string
}
options.truncate -= 4
options.seen = options.seen || []
if (options.seen.indexOf(object) >= 0) {
if (options.seen.includes(object)) {
return '[Circular]'
}
options.seen.push(object)
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 983691f

Please sign in to comment.