mirror of
https://github.com/chenasraf/massarg.git
synced 2026-05-18 01:39:05 +00:00
fix: async run error handling
This commit is contained in:
@@ -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)) {
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user