Skip to content

Commit

Permalink
Spawn handler: wrap the program call with try/catch, exit gracefully …
Browse files Browse the repository at this point in the history
…on error (#1320)

Prevents unhandled rejections when the spawned program crashes.

## Testing Instructions

Confirm CI tests pass
  • Loading branch information
adamziel authored Apr 25, 2024
1 parent f0250e0 commit 3d15529
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
21 changes: 21 additions & 0 deletions packages/php-wasm/util/src/lib/create-spawn-handler.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,25 @@ describe('createSpawnHandler', () => {
});
});
});

it('should exit with code 1 when the spawned process throws an exception', async () => {
const command = 'testCommand';
const program = vitest.fn(() => {
throw new Error('Program crash');
});

const spawnHandler = createSpawnHandler(program);
const childProcess = spawnHandler(command);

const errorfn = vitest.fn();
await new Promise((done) => {
childProcess.on('error', errorfn);
childProcess.on('exit', (code: number) => {
expect(code).toBe(1);
expect(program).toHaveBeenCalled();
done(null);
});
});
expect(errorfn).toHaveBeenCalledWith(new Error('Program crash'));
});
});
15 changes: 14 additions & 1 deletion packages/php-wasm/util/src/lib/create-spawn-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,20 @@ export function createSpawnHandler(
} else {
throw new Error('Invalid command ', command);
}
await program(commandArray, processApi, options);
try {
await program(commandArray, processApi, options);
} catch (e) {
childProcess.emit('error', e);
if (
typeof e === 'object' &&
e !== null &&
'message' in e &&
typeof e.message === 'string'
) {
processApi.stderr(e.message);
}
processApi.exit(1);
}
childProcess.emit('spawn', true);
});
return childProcess;
Expand Down

0 comments on commit 3d15529

Please sign in to comment.