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

Spawn handler: wrap the program call with try/catch, exit gracefully on error #1320

Merged
merged 1 commit into from
Apr 25, 2024
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
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
Loading