Skip to content

Commit

Permalink
feat: Add support for serializing Error causes
Browse files Browse the repository at this point in the history
  • Loading branch information
Nokel81 committed Feb 14, 2024
1 parent 288a906 commit 6a8a91e
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
2 changes: 1 addition & 1 deletion pack.js
Original file line number Diff line number Diff line change
Expand Up @@ -896,7 +896,7 @@ extensions = [{
target[position++] = 0x65 // 'e' for error
target[position++] = 0
}
pack([ error.name, error.message ])
pack([ error.name, error.message, error.cause ])
}
}, {
pack(regex, allocateForWrite, pack) {
Expand Down
18 changes: 18 additions & 0 deletions tests/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -703,6 +703,24 @@ suite('msgpackr basic tests', function() {
}
})

test('moreTyesp: Error with causes', function() {
const object = {
error: new Error('test'),
errorWithCause: new Error('test-1', { cause: new Error('test-2')}),
}
const packr = new Packr({
moreTypes: true,
})

const serialized = packr.pack(object)
const deserialized = packr.unpack(serialized)
assert.equal(deserialized.error.message, object.error.message)
assert.equal(deserialized.error.cause, object.error.cause)
assert.equal(deserialized.errorWithCause.message, object.errorWithCause.message)
assert.equal(deserialized.errorWithCause.cause.message, object.errorWithCause.cause.message)
assert.equal(deserialized.errorWithCause.cause.cause, object.errorWithCause.cause.cause)
})

test('structured cloning: self reference', function() {
let object = {
test: 'string',
Expand Down
2 changes: 1 addition & 1 deletion unpack.js
Original file line number Diff line number Diff line change
Expand Up @@ -1010,7 +1010,7 @@ currentExtensions[0x42] = (data) => {
let errors = { Error, TypeError, ReferenceError };
currentExtensions[0x65] = () => {
let data = read()
return (errors[data[0]] || Error)(data[1])
return (errors[data[0]] || Error)(data[1], { cause: data[2] })
}

currentExtensions[0x69] = (data) => {
Expand Down

0 comments on commit 6a8a91e

Please sign in to comment.