Skip to content

Commit 922b7e4

Browse files
committed
feat: print custom or default error when opts.unknown tripped
1 parent 206188a commit 922b7e4

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

lib/index.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,9 @@ class Sade {
135135
opts.default = Object.assign(all.default, cmd.default, opts.default);
136136

137137
let vals = mri(arr.slice(offset), opts);
138-
if (!vals) return;
138+
if (!vals || typeof vals === 'string') {
139+
return $.error(bin, vals || 'Parsed unknown option flag(s)!');
140+
}
139141

140142
let segs = cmd.usage.split(/\s+/);
141143
let reqs = segs.filter(x => x.charAt(0)==='<');

readme.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,33 @@ prog.parse(process.argv, {
413413
//=> ADDS default: abc -> 123 (number)
414414
```
415415

416+
#### opts.unknown
417+
418+
Type: `Function`<br>
419+
Default: `undefined`
420+
421+
Callback to run when an unspecified option flag has been found. This is [passed directly to `mri`](https://github.com/lukeed/mri#optionsunknown).
422+
423+
Your handler will receive the unknown flag (string) as its only argument.<br>
424+
You may return a string, which will be used as a custom error message. Otherwise, a default message is displayed.
425+
426+
```js
427+
sade('sirv')
428+
.command('start [dir]')
429+
.parse(process.argv, {
430+
unknown: arg => `Custom error message: ${arg}`
431+
});
432+
433+
/*
434+
$ sirv start --foobar
435+
436+
ERROR
437+
Custom error message: --foobar
438+
439+
Run `$ sirv --help` for more info.
440+
*/
441+
```
442+
416443
#### opts.lazy
417444

418445
Type: `Boolean`<br>

0 commit comments

Comments
 (0)