Skip to content

Commit 3e13abe

Browse files
committed
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?
1 parent 3c18460 commit 3e13abe

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

index.js

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,5 +151,19 @@ if (!nativeBinding) {
151151

152152
const { compress, decompress } = nativeBinding;
153153

154-
module.exports.compress = compress;
155-
module.exports.decompress = decompress;
154+
// Error objects created via napi don't have JS stacks; wrap them so .stack is present
155+
// https://github.com/nodejs/node/issues/25318#issuecomment-451068073
156+
module.exports.compress = async function (data) {
157+
try {
158+
return await compress(data);
159+
} catch (e) {
160+
throw new Error(`zstd: ${e.message}`);
161+
}
162+
};
163+
module.exports.decompress = async function (data) {
164+
try {
165+
return await decompress(data);
166+
} catch (e) {
167+
throw new Error(`zstd: ${e.message}`);
168+
}
169+
};

test/index.test.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,17 @@ describe('zstd', () => {
3737
});
3838
});
3939
});
40+
41+
describe('#decompress', () => {
42+
context('when decompressing invalid data', () => {
43+
it('includes a stack trace', async () => {
44+
try {
45+
await decompress(Buffer.from('invalid'));
46+
} catch (error) {
47+
expect(error.message).to.be('zstd: Unknown frame descriptor');
48+
expect(error.stack).to.match(/at decompress/);
49+
}
50+
}
51+
});
52+
});
4053
});

0 commit comments

Comments
 (0)