fix: async run error handling

This commit is contained in:
2026-01-26 12:01:06 +02:00
parent 464f0b6400
commit 4de92efef2
2 changed files with 29 additions and 2 deletions

View File

@@ -399,7 +399,18 @@ export class MassargCommand<Args extends ArgsObject = ArgsObject>
process.on('unhandledRejection', handleRejection)
try {
this.getArgs(argv, args, parent, true)
const result = this.getArgs(argv, args, parent, true)
// Handle async run functions
if (result instanceof Promise) {
return result
.then(() => cleanup())
.catch((e) => {
cleanup()
this.handleError(e)
})
}
cleanup()
} catch (e) {
cleanup()
@@ -520,7 +531,7 @@ export class MassargCommand<Args extends ArgsObject = ArgsObject>
// no sub command found, run main command
if (this._run) {
this._run(this.args as Args, parent ?? this)
return this._run(this.args as Args, parent ?? this)
}
} catch (e) {
if (isZodError(e)) {

View File

@@ -309,4 +309,20 @@ describe('onError', () => {
expect(handler).toHaveBeenCalled()
expect(handler.mock.calls[0][0].message).toBe('sub error')
})
test('error handler catches async errors', async () => {
const handler = vi.fn()
const command = massarg(opts)
.onError(handler)
.main(async () => {
await Promise.resolve()
throw new Error('async error')
})
await command.parse([])
expect(handler).toHaveBeenCalled()
expect(handler.mock.calls[0][0].message).toBe('async error')
expect(mockExit).toHaveBeenCalledWith(1)
})
})