Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: prevent callback from triggering twice when callback throws #681

Merged
merged 1 commit into from
Aug 31, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/__tests__/volume/callback-error.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
jest.useFakeTimers('modern');

// Fixes https://github.com/streamich/memfs/issues/542
it('should throw error instead of callback', () => {
const { Volume } = require('../../volume');
const vol = new Volume();

vol.writeFile('/asdf.txt', 'asdf', 'utf8', (err) => {
if (!err) {
throw new Error('try to trigger catch');
}
});

expect(() => jest.runAllTimers()).toThrow('try to trigger catch');
});
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since wrapAsync uses setImmediate to invoke the callback that throws an error, the error can't be caught.

The only way to catch it seemed to be by stubbing setImmediate, which the jest.useFakerTimers() at the top does. This queues all callbacks until jest.runAllTimers() is invoked, which runs the queued callbacks synchronously to catch the error being thrown.

jest.useFakerTimers() seemed to stub setImmediate for all tests in the file, so I had to put it in a separate file to only influence this specific test.

5 changes: 4 additions & 1 deletion src/volume.ts
Original file line number Diff line number Diff line change
Expand Up @@ -826,11 +826,14 @@ export class Volume {
private wrapAsync(method: (...args) => void, args: any[], callback: TCallback<any>) {
validateCallback(callback);
setImmediate(() => {
let result;
try {
callback(null, method.apply(this, args));
result = method.apply(this, args);
} catch (err) {
callback(err);
return;
}
callback(null, result);
});
}

Expand Down