yargs: Sync error of handler should throw a global error
// foo.js
'use strict';
const yargs = require('yargs');
yargs
.help('help').alias('help', 'h')
.command('foo', 'Foo command is awesome', () => {
console.log('foo handler');
throw new Error('This error will show below the help');
})
.argv;
If you now run node foo
it will show the usage and the error below.

I was expecting the error to be thrown globally and not being handled by yargs.
yargs version: 4.3.2
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Comments: 17 (16 by maintainers)
@satazor I had this exact same discussion over lunch with @iarna last week; I agree that we shouldn’t be handling runtime errors, and would like to figure out a better approach in the command handlers.
@satazor basically, are you thinking that we track all the errors that yargs itself generates, perhaps with a special key on the Error object, and throw anything we don’t know about?
Well kind of. I expect yargs to not handle errors that come from command handlers (language or throw on purpose), because as I see it, when the handler is invoked, yargs has done its job.
@satazor hope all is well 😃
I’ve finished releasing yargs@7 which introduces its own error class, and should bubble application-level errors to the top. Would love your help testing the 7.x release (which is a pretty big refactor):
npm cache clear; npm i yargs@next
CC: @iarna
I got the same problem as @satazor and I fully support his proposal.
No, not easily. The problem is that
fail()
is called with an error message and not an Error instance, so I have no access to the stack directly. Even if it was called with an Error instance I had to distinguish between TypeError among others to either show the stack trace & exit or print the help usage.