CLI11  1.9.0
Error.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 // Distributed under the 3-Clause BSD License. See accompanying
4 // file LICENSE or https://github.com/CLIUtils/CLI11 for details.
5 
6 #include <exception>
7 #include <stdexcept>
8 #include <string>
9 #include <utility>
10 
11 // CLI library includes
12 #include "CLI/StringTools.hpp"
13 
14 namespace CLI {
15 
16 // Use one of these on all error classes.
17 // These are temporary and are undef'd at the end of this file.
18 #define CLI11_ERROR_DEF(parent, name) \
19  protected: \
20  name(std::string ename, std::string msg, int exit_code) : parent(std::move(ename), std::move(msg), exit_code) {} \
21  name(std::string ename, std::string msg, ExitCodes exit_code) \
22  : parent(std::move(ename), std::move(msg), exit_code) {} \
23  \
24  public: \
25  name(std::string msg, ExitCodes exit_code) : parent(#name, std::move(msg), exit_code) {} \
26  name(std::string msg, int exit_code) : parent(#name, std::move(msg), exit_code) {}
27 
28 // This is added after the one above if a class is used directly and builds its own message
29 #define CLI11_ERROR_SIMPLE(name) \
30  explicit name(std::string msg) : name(#name, msg, ExitCodes::name) {}
31 
34 enum class ExitCodes {
35  Success = 0,
39  FileError,
51  BaseClass = 127
52 };
53 
54 // Error definitions
55 
61 
63 class Error : public std::runtime_error {
64  int actual_exit_code;
65  std::string error_name{"Error"};
66 
67  public:
68  int get_exit_code() const { return actual_exit_code; }
69 
70  std::string get_name() const { return error_name; }
71 
72  Error(std::string name, std::string msg, int exit_code = static_cast<int>(ExitCodes::BaseClass))
73  : runtime_error(msg), actual_exit_code(exit_code), error_name(std::move(name)) {}
74 
75  Error(std::string name, std::string msg, ExitCodes exit_code) : Error(name, msg, static_cast<int>(exit_code)) {}
76 };
77 
78 // Note: Using Error::Error constructors does not work on GCC 4.7
79 
81 class ConstructionError : public Error {
83 };
84 
89  static IncorrectConstruction PositionalFlag(std::string name) {
90  return IncorrectConstruction(name + ": Flags cannot be positional");
91  }
92  static IncorrectConstruction Set0Opt(std::string name) {
93  return IncorrectConstruction(name + ": Cannot set 0 expected, use a flag instead");
94  }
95  static IncorrectConstruction SetFlag(std::string name) {
96  return IncorrectConstruction(name + ": Cannot set an expected number for flags");
97  }
98  static IncorrectConstruction ChangeNotVector(std::string name) {
99  return IncorrectConstruction(name + ": You can only change the expected arguments for vectors");
100  }
101  static IncorrectConstruction AfterMultiOpt(std::string name) {
102  return IncorrectConstruction(
103  name + ": You can't change expected arguments after you've changed the multi option policy!");
104  }
105  static IncorrectConstruction MissingOption(std::string name) {
106  return IncorrectConstruction("Option " + name + " is not defined");
107  }
108  static IncorrectConstruction MultiOptionPolicy(std::string name) {
109  return IncorrectConstruction(name + ": multi_option_policy only works for flags and exact value options");
110  }
111 };
112 
117  static BadNameString OneCharName(std::string name) { return BadNameString("Invalid one char name: " + name); }
118  static BadNameString BadLongName(std::string name) { return BadNameString("Bad long name: " + name); }
119  static BadNameString DashesOnly(std::string name) {
120  return BadNameString("Must have a name, not just dashes: " + name);
121  }
122  static BadNameString MultiPositionalNames(std::string name) {
123  return BadNameString("Only one positional name allowed, remove: " + name);
124  }
125 };
126 
130  explicit OptionAlreadyAdded(std::string name)
131  : OptionAlreadyAdded(name + " is already added", ExitCodes::OptionAlreadyAdded) {}
132  static OptionAlreadyAdded Requires(std::string name, std::string other) {
133  return OptionAlreadyAdded(name + " requires " + other, ExitCodes::OptionAlreadyAdded);
134  }
135  static OptionAlreadyAdded Excludes(std::string name, std::string other) {
136  return OptionAlreadyAdded(name + " excludes " + other, ExitCodes::OptionAlreadyAdded);
137  }
138 };
139 
140 // Parsing errors
141 
143 class ParseError : public Error {
145 };
146 
147 // Not really "errors"
148 
150 class Success : public ParseError {
152  Success() : Success("Successfully completed, should be caught and quit", ExitCodes::Success) {}
153 };
154 
156 class CallForHelp : public ParseError {
158  CallForHelp() : CallForHelp("This should be caught in your main function, see examples", ExitCodes::Success) {}
159 };
160 
162 class CallForAllHelp : public ParseError {
165  : CallForAllHelp("This should be caught in your main function, see examples", ExitCodes::Success) {}
166 };
167 
169 class RuntimeError : public ParseError {
171  explicit RuntimeError(int exit_code = 1) : RuntimeError("Runtime error", exit_code) {}
172 };
173 
175 class FileError : public ParseError {
178  static FileError Missing(std::string name) { return FileError(name + " was not readable (missing?)"); }
179 };
180 
182 class ConversionError : public ParseError {
185  ConversionError(std::string member, std::string name)
186  : ConversionError("The value " + member + " is not an allowed value for " + name) {}
187  ConversionError(std::string name, std::vector<std::string> results)
188  : ConversionError("Could not convert: " + name + " = " + detail::join(results)) {}
189  static ConversionError TooManyInputsFlag(std::string name) {
190  return ConversionError(name + ": too many inputs for a flag");
191  }
192  static ConversionError TrueFalse(std::string name) {
193  return ConversionError(name + ": Should be true/false or a number");
194  }
195 };
196 
198 class ValidationError : public ParseError {
201  explicit ValidationError(std::string name, std::string msg) : ValidationError(name + ": " + msg) {}
202 };
203 
205 class RequiredError : public ParseError {
207  explicit RequiredError(std::string name) : RequiredError(name + " is required", ExitCodes::RequiredError) {}
208  static RequiredError Subcommand(std::size_t min_subcom) {
209  if(min_subcom == 1) {
210  return RequiredError("A subcommand");
211  }
212  return RequiredError("Requires at least " + std::to_string(min_subcom) + " subcommands",
214  }
215  static RequiredError
216  Option(std::size_t min_option, std::size_t max_option, std::size_t used, const std::string &option_list) {
217  if((min_option == 1) && (max_option == 1) && (used == 0))
218  return RequiredError("Exactly 1 option from [" + option_list + "]");
219  if((min_option == 1) && (max_option == 1) && (used > 1)) {
220  return RequiredError("Exactly 1 option from [" + option_list + "] is required and " + std::to_string(used) +
221  " were given",
223  }
224  if((min_option == 1) && (used == 0))
225  return RequiredError("At least 1 option from [" + option_list + "]");
226  if(used < min_option) {
227  return RequiredError("Requires at least " + std::to_string(min_option) + " options used and only " +
228  std::to_string(used) + "were given from [" + option_list + "]",
230  }
231  if(max_option == 1)
232  return RequiredError("Requires at most 1 options be given from [" + option_list + "]",
234 
235  return RequiredError("Requires at most " + std::to_string(max_option) + " options be used and " +
236  std::to_string(used) + "were given from [" + option_list + "]",
238  }
239 };
240 
242 class ArgumentMismatch : public ParseError {
245  ArgumentMismatch(std::string name, int expected, std::size_t recieved)
246  : ArgumentMismatch(expected > 0 ? ("Expected exactly " + std::to_string(expected) + " arguments to " + name +
247  ", got " + std::to_string(recieved))
248  : ("Expected at least " + std::to_string(-expected) + " arguments to " + name +
249  ", got " + std::to_string(recieved)),
251 
252  static ArgumentMismatch AtLeast(std::string name, int num, std::size_t received) {
253  return ArgumentMismatch(name + ": At least " + std::to_string(num) + " required but received " +
254  std::to_string(received));
255  }
256  static ArgumentMismatch AtMost(std::string name, int num, std::size_t received) {
257  return ArgumentMismatch(name + ": At Most " + std::to_string(num) + " required but received " +
258  std::to_string(received));
259  }
260  static ArgumentMismatch TypedAtLeast(std::string name, int num, std::string type) {
261  return ArgumentMismatch(name + ": " + std::to_string(num) + " required " + type + " missing");
262  }
263  static ArgumentMismatch FlagOverride(std::string name) {
264  return ArgumentMismatch(name + " was given a disallowed flag override");
265  }
266 };
267 
269 class RequiresError : public ParseError {
271  RequiresError(std::string curname, std::string subname)
272  : RequiresError(curname + " requires " + subname, ExitCodes::RequiresError) {}
273 };
274 
276 class ExcludesError : public ParseError {
278  ExcludesError(std::string curname, std::string subname)
279  : ExcludesError(curname + " excludes " + subname, ExitCodes::ExcludesError) {}
280 };
281 
283 class ExtrasError : public ParseError {
285  explicit ExtrasError(std::vector<std::string> args)
286  : ExtrasError((args.size() > 1 ? "The following arguments were not expected: "
287  : "The following argument was not expected: ") +
288  detail::rjoin(args, " "),
290  ExtrasError(const std::string &name, std::vector<std::string> args)
291  : ExtrasError(name,
292  (args.size() > 1 ? "The following arguments were not expected: "
293  : "The following argument was not expected: ") +
294  detail::rjoin(args, " "),
296 };
297 
299 class ConfigError : public ParseError {
302  static ConfigError Extras(std::string item) { return ConfigError("INI was not able to parse " + item); }
303  static ConfigError NotConfigurable(std::string item) {
304  return ConfigError(item + ": This option is not allowed in a configuration file");
305  }
306 };
307 
309 class InvalidError : public ParseError {
311  explicit InvalidError(std::string name)
312  : InvalidError(name + ": Too many positional arguments with unlimited expected args", ExitCodes::InvalidError) {
313  }
314 };
315 
318 class HorribleError : public ParseError {
321 };
322 
323 // After parsing
324 
326 class OptionNotFound : public Error {
328  explicit OptionNotFound(std::string name) : OptionNotFound(name + " not found", ExitCodes::OptionNotFound) {}
329 };
330 
331 #undef CLI11_ERROR_DEF
332 #undef CLI11_ERROR_SIMPLE
333 
335 
336 } // namespace CLI
CLI::FileError
Thrown when parsing an INI file and it is missing.
Definition: Error.hpp:175
CLI::ExitCodes::ArgumentMismatch
@ ArgumentMismatch
CLI::ExitCodes::ExtrasError
@ ExtrasError
CLI::detail::rjoin
std::string rjoin(const T &v, std::string delim=",")
Join a string in reverse order.
Definition: StringTools.hpp:85
CLI::ExitCodes::ConversionError
@ ConversionError
CLI::ExitCodes::BaseClass
@ BaseClass
CLI::ExcludesError
Thrown when an excludes option is present.
Definition: Error.hpp:276
CLI::Success
This is a successful completion on parsing, supposed to exit.
Definition: Error.hpp:150
CLI::CallForHelp
-h or –help on command line
Definition: Error.hpp:156
CLI::ParseError
Anything that can error in Parse.
Definition: Error.hpp:143
CLI::ExitCodes::Success
@ Success
CLI::Error::Error
Error(std::string name, std::string msg, ExitCodes exit_code)
Definition: Error.hpp:75
CLI::ExtrasError
Thrown when too many positionals or options are found.
Definition: Error.hpp:283
CLI::ExitCodes
ExitCodes
Definition: Error.hpp:34
CLI::ConversionError
Thrown when conversion call back fails, such as when an int fails to coerce to a string.
Definition: Error.hpp:182
CLI::ExitCodes::OptionAlreadyAdded
@ OptionAlreadyAdded
CLI::detail::join
std::string join(const T &v, std::string delim=",")
Simple function to join a string.
Definition: StringTools.hpp:56
CLI::ExitCodes::RequiresError
@ RequiresError
CLI::ExitCodes::FileError
@ FileError
CLI::MultiOptionPolicy
MultiOptionPolicy
Enumeration of the multiOption Policy selection.
Definition: Option.hpp:32
CLI::detail::to_string
auto to_string(T &&value) -> decltype(std::forward< T >(value))
Convert an object to a string (directly forward if this can become a string)
Definition: TypeTools.hpp:222
CLI::Error::get_exit_code
int get_exit_code() const
Definition: Error.hpp:68
CLI::RuntimeError
Does not output a diagnostic in CLI11_PARSE, but allows to return from main() with a specific error c...
Definition: Error.hpp:169
CLI::ExitCodes::RequiredError
@ RequiredError
CLI
Definition: App.hpp:27
CLI11_ERROR_DEF
#define CLI11_ERROR_DEF(parent, name)
Definition: Error.hpp:18
CLI::ExitCodes::OptionNotFound
@ OptionNotFound
CLI::Error::get_name
std::string get_name() const
Definition: Error.hpp:70
CLI::BadNameString
Thrown on construction of a bad name.
Definition: Error.hpp:114
CLI::ConstructionError
Construction errors (not in parsing)
Definition: Error.hpp:81
CLI::Error
All errors derive from this one.
Definition: Error.hpp:63
CLI::OptionAlreadyAdded
Thrown when an option already exists.
Definition: Error.hpp:128
CLI::Option
Definition: Option.hpp:228
CLI::ExitCodes::InvalidError
@ InvalidError
CLI::ExitCodes::BadNameString
@ BadNameString
CLI::ValidationError
Thrown when validation of results fails.
Definition: Error.hpp:198
StringTools.hpp
CLI::InvalidError
Thrown when validation fails before parsing.
Definition: Error.hpp:309
CLI::Error::Error
Error(std::string name, std::string msg, int exit_code=static_cast< int >(ExitCodes::BaseClass))
Definition: Error.hpp:72
CLI::ExitCodes::ConfigError
@ ConfigError
CLI::ExitCodes::ExcludesError
@ ExcludesError
CLI::CallForAllHelp
Usually something like –help-all on command line.
Definition: Error.hpp:162
CLI::ArgumentMismatch
Thrown when the wrong number of arguments has been received.
Definition: Error.hpp:242
CLI::HorribleError
Definition: Error.hpp:318
CLI::RequiredError
Thrown when a required option is missing.
Definition: Error.hpp:205
CLI11_ERROR_SIMPLE
#define CLI11_ERROR_SIMPLE(name)
Definition: Error.hpp:29
CLI::OptionNotFound
Thrown when counting a non-existent option.
Definition: Error.hpp:326
CLI::ConfigError
Thrown when extra values are found in an INI file.
Definition: Error.hpp:299
CLI::ExitCodes::ValidationError
@ ValidationError
CLI::IncorrectConstruction
Thrown when an option is set to conflicting values (non-vector and multi args, for example)
Definition: Error.hpp:86
CLI::RequiresError
Thrown when a requires option is missing.
Definition: Error.hpp:269
CLI::ExitCodes::HorribleError
@ HorribleError