Skip to content

Commit

Permalink
feat: yargs is now passed as the third-argument to fail handler (yarg…
Browse files Browse the repository at this point in the history
  • Loading branch information
mkawalec authored and bcoe committed Nov 13, 2016
1 parent 54cb31d commit 21b74f9
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
8 changes: 5 additions & 3 deletions README.md
Expand Up @@ -1150,15 +1150,17 @@ yargs have been validated.

Method to execute when a failure occurs, rather than printing the failure message.

`fn` is called with the failure message that would have been printed and the
`Error` instance originally thrown, if any.
`fn` is called with the failure message that would have been printed, the
`Error` instance originally thrown and yargs state when the failure
occured.

```js
var argv = require('yargs')
.fail(function (msg, err) {
.fail(function (msg, err, yargs) {
if (err) throw err // preserve stack
console.error('You broke it!')
console.error(msg)
console.error('You should be doing', yargs.help())
process.exit(1)
})
.argv
Expand Down
2 changes: 1 addition & 1 deletion lib/usage.js
Expand Up @@ -34,7 +34,7 @@ module.exports = function (yargs, y18n) {

if (fails.length) {
for (var i = fails.length - 1; i >= 0; --i) {
fails[i](msg, err)
fails[i](msg, err, self)
}
} else {
if (yargs.getExitProcess()) setBlocking(true)
Expand Down
22 changes: 22 additions & 0 deletions test/usage.js
Expand Up @@ -473,6 +473,28 @@ describe('usage tests', function () {
r.logs.should.deep.equal(['foo'])
r.should.have.property('exit').and.be.false
})

it('gives the ability to log a per-command error message if failure occurs in a command', function () {
var r = checkUsage(function () {
return yargs('foo')
.command('foo', 'desc', {
bar: {
describe: 'bar command'
}
}, function (argv) {
throw new Error('blah')
})
.fail(function (message, error, yargs) {
yargs.showHelp()
})
.exitProcess(false)
.wrap(null)
.argv
})

r.errors[0].should.contain('bar command')
})

describe('when check() throws error', function () {
it('fail() is called with the original error object as the second parameter', function () {
var r = checkUsage(function () {
Expand Down

0 comments on commit 21b74f9

Please sign in to comment.