Skip to content

Commit

Permalink
Wrap thrown errors in JS Error objects with stacks
Browse files Browse the repository at this point in the history
We noticed in our usage of this package that thrown errors (eg: "Unknown frame descriptor") don't have a useful .stack property. This makes debugging harder. It seems this is expected behavior for errors created via napi at least on V8; it seems that the best way to remedy this is to recreate Error objects on the JS side?
  • Loading branch information
sophiebits committed Aug 27, 2024
1 parent 3c18460 commit c53e517
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
18 changes: 16 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,5 +151,19 @@ if (!nativeBinding) {

const { compress, decompress } = nativeBinding;

module.exports.compress = compress;
module.exports.decompress = decompress;
// Error objects created via napi don't have JS stacks; wrap them so .stack is present
// https://github.com/nodejs/node/issues/25318#issuecomment-451068073
module.exports.compress = async function (data) {
try {
return await compress(data);
} catch (e) {
throw new Error(`zstd: ${e.message}`);
}
};
module.exports.decompress = async function (data) {
try {
return await decompress(data);
} catch (e) {
throw new Error(`zstd: ${e.message}`);
}
};
13 changes: 13 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,17 @@ describe('zstd', () => {
});
});
});

describe('#decompress', () => {
context('when decompressing invalid data', () => {
it('includes a stack trace', async () => {
try {
await decompress(Buffer.from('invalid'));
} catch (error) {
expect(error.message).to.be('zstd: Unknown frame descriptor');
expect(error.stack).to.match(/at decompress/);
}
});
});
});
});

0 comments on commit c53e517

Please sign in to comment.