Skip to content

Commit

Permalink
Serialize errors with cause (pinojs#105)
Browse files Browse the repository at this point in the history
* Add (failing) test for serialization of causes of errors

* Add cause serialization to error serializer

The error serializer already handles the case where an error is not of type Error (or AggregateError) well, so there is no reason to add special handling for that. We can simply pass whatever is in `cause` into the serializer, and we should get a serialized result out.

* Add `cause` to errors in similar way to what is done in other errors

* Expand cause serialization test to show recursion
  • Loading branch information
hypesystem authored Jun 10, 2022
1 parent c40269b commit ae83956
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/err.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ const pinoErrProto = Object.create({}, {
writable: true,
value: undefined
},
cause: {
enumerable: true,
writable: true,
value: undefined
},
raw: {
enumerable: false,
get: function () {
Expand Down Expand Up @@ -60,6 +65,10 @@ function errSerializer (err) {
_err.aggregateErrors = err.errors.map(err => errSerializer(err))
}

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

for (const key in err) {
if (_err[key] === undefined) {
const val = err[key]
Expand Down
24 changes: 24 additions & 0 deletions test/err.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -194,3 +194,27 @@ test('serializes aggregate errors', { skip: !global.AggregateError }, function (
t.match(serialized.aggregateErrors[1].stack, /^Error: bar/)
t.match(serialized.stack, /err\.test\.js:/)
})

test('serializes causes', function (t) {
t.plan(11)

const bar = new Error('bar')
bar.cause = new Error('foo')
bar.cause.cause = new Error('baz')

const serialized = serializer(bar)

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

t.ok(serialized.cause)
t.equal(serialized.cause.type, 'Error')
t.equal(serialized.cause.message, 'foo: baz')
t.match(serialized.cause.stack, /err\.test\.js:/)

t.ok(serialized.cause.cause)
t.equal(serialized.cause.cause.type, 'Error')
t.equal(serialized.cause.cause.message, 'baz')
t.match(serialized.cause.cause.stack, /err\.test\.js:/)
})

0 comments on commit ae83956

Please sign in to comment.