Skip to content

Commit 1a0ff79

Browse files
committed
Improve error handling for unrecognized arguments
When command doesn't register handler for anonymous arguments, the error description looks broken: "Error: unknown flag: ". This commit improves error reporting logic, providing the name of misspelled subcommand or unrecognized argument: "Error: unrecognized arg: foo".
1 parent b06e867 commit 1a0ff79

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

include/args.hpp

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -353,9 +353,14 @@ struct context
353353
this->add(std::move(arg));
354354
}
355355

356+
bool is_known_flag(const std::string& flag) const noexcept
357+
{
358+
return lookup.find(flag) != lookup.end();
359+
}
360+
356361
argument& operator[](const std::string& flag)
357362
{
358-
if (lookup.find(flag) == lookup.end())
363+
if (!is_known_flag(flag))
359364
{
360365
throw std::runtime_error("unknown flag: " + flag);
361366
}
@@ -365,7 +370,7 @@ struct context
365370

366371
const argument& operator[](const std::string& flag) const
367372
{
368-
if (lookup.find(flag) == lookup.end())
373+
if (!is_known_flag(flag))
369374
{
370375
throw std::runtime_error("unknown flag: " + flag);
371376
}
@@ -627,7 +632,14 @@ void parse(T& cmd, std::deque<std::string> a, Ts&&... xs)
627632
ctx.subcommands[x].run(drop(a), cmd, xs...);
628633
break;
629634
}
630-
else if (ctx[""].write(x)) return;
635+
else if (ctx.is_known_flag(""))
636+
{
637+
if (ctx[""].write(x)) return;
638+
}
639+
else
640+
{
641+
throw std::runtime_error("unrecognized arg: " + x);
642+
}
631643
}
632644
}
633645
ctx.post_process();

0 commit comments

Comments
 (0)