nodeca / argparse

CLI arguments parser for node.js. JS port of python's argparse module.
Other
487 stars 73 forks source link

error thrown from type function not included in console message #140

Closed dcopp closed 4 years ago

dcopp commented 5 years ago
// typefail.js
'use strict';

// repro: node typefail.js foo
//
// actual result (console output):
//   usage: typefail.js [-h] json_fn
//   typefail.js: error: argument "json_fn": Invalid jsonFile value: foo
//
// expected result:
//   usage: typefail.js [-h] json_fn
//   typefail.js: error: argument "json_fn": Invalid jsonFile value: foo
//   this message should appear in the console, but does not

const { ArgumentParser } = require('argparse');

function jsonFile(fn) {
    //return JSON.parse(fs.readFileSync(fn, 'utf8'));
    throw new Error('this message should appear in the console, but does not');
}

const parser = ArgumentParser();
parser.addArgument('fn', {
    metavar: 'json_fn',
    type: jsonFile,
});

const args = parser.parseArgs();
console.log(args);

In lib/argument_parser.js there is

`name = action.type.name || action.type.displayName || '<function>';`

The action.type.name expression sets name to the name of the function (under nodejs at least). Later a check fails

`if (name === '<function>') { msg += '\n' + e.message; }`

because of course '<function>' not the name of the function. And anyway there is no ambiguity here that we are dealing with a function that threw, so why be conditional about including the exception message?

This is a fairly serious omission in that when using a type function to implement validation on arguments, invalid input is never accompanied by the message intended to indicate why it is invalid.

rlidwka commented 4 years ago

This error seem to have fixed itself after we've ported everything from scratch based on python 3.9 (released as argparse version 2.0).

Please open a new issue if there's still something wrong there.