Skip to content

Commit

Permalink
Fix evaluateCause loosing access to this
Browse files Browse the repository at this point in the history
  • Loading branch information
KoltesDigital committed Jun 13, 2022
1 parent d8ce240 commit 01cbb10
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 13 deletions.
12 changes: 6 additions & 6 deletions lib/err-helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,22 @@
const getErrorCause = (err) => {
if (!err) return

const cause = evaluateCause(err.cause)
const cause = evaluateCause(err)

return cause instanceof Error
? cause
: undefined
}

/**
* @param {unknown|(()=>err)} cause
* @param {Error|{ cause?: unknown|(()=>err)}} err
* @returns {Error|undefined}
*/
const evaluateCause = (cause) => {
const evaluateCause = (err) => {
// VError / NError style causes are functions
return typeof cause === 'function'
? cause()
: cause
return typeof err.cause === 'function'
? err.cause()
: err.cause
}

/**
Expand Down
2 changes: 1 addition & 1 deletion lib/err.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ function errSerializer (err) {
}

if (err.cause) {
const cause = evaluateCause(err.cause)
const cause = evaluateCause(err)
_err.cause = errSerializer(cause)
}

Expand Down
22 changes: 16 additions & 6 deletions test/err.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -223,16 +223,26 @@ test('serializes causes with VError support', function (t) {
t.plan(11)

// Fake VError-style setup
const err = Error('foo: bar')
err.cause = () => {
const err = Error('bar')
err.cause = Error('abc')
return err
class VError extends Error {
constructor (message, cause) {
super(message + ': ' + cause.message)
this._cause = cause
}

// Ensure `cause` refers `this` (see https://github.com/pinojs/pino-std-serializers/pull/109)
cause () {
return this._cause
}
}

const causeErr = Error('bar')
causeErr.cause = Error('abc')

const err = new VError('foo', causeErr)

const serialized = serializer(err)

t.equal(serialized.type, 'Error')
t.equal(serialized.type, 'VError')
t.equal(serialized.message, 'foo: bar: abc') // message serialization already walks cause-chain
t.match(serialized.stack, /err\.test\.js:/)

Expand Down

0 comments on commit 01cbb10

Please sign in to comment.