From 3e13abe3a83e50751777e7bdb1dfa9eb7fcdf1f0 Mon Sep 17 00:00:00 2001 From: Sophie Alpert Date: Mon, 26 Aug 2024 17:46:21 -0700 Subject: [PATCH] Wrap thrown errors in JS Error objects with stacks 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? --- index.js | 18 ++++++++++++++++-- test/index.test.js | 13 +++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index e411226..6c15cbb 100644 --- a/index.js +++ b/index.js @@ -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}`); + } +}; diff --git a/test/index.test.js b/test/index.test.js index 781f005..6a669fc 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -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/); + } + } + }); + }); });