Exception Handling - adamtomi/grapefruit GitHub Wiki

Out-of-the-box Behaviour

Since grapefruit v1.2 it's possible to register custom exception handlers for all subclasses of CommandException. The default behaviour is that a user frienly message related to given exception is printed using the Messenger supplied by CommandDispatcherBuilder#withMessenger. It should be sufficient to cover most cases, but if this doesn't meet your needs, you can specify your own handlers.

List Of Exceptions

Currently, this is the list of all subclasses of CommandException:

  • CommandAuthorizationException - Thrown when a user lacks the required permission by a command.
  • CommandInvocationException - Wraps all kinds of Throwables; this exception indicates that something went seriously wrong while executing a certain command.
  • CommandSyntaxException - Thrown when the given syntax is not valid. One common (albeit not the only) cause of this exception is invalid number of arguments.
  • FlagDuplicateException - Grapefruit does not support multi flags at the moment (which look something like this: someparams --flag firstValue --flag secondValue), so in a flag appears multiple times a single command line, this exception will be thrown.
  • IllegalCommandSourceException - Some commands require special kind of source types. If that criteria is not matched, this exception will be thrown.
  • NoSuchCommandException - Thrown when the specified command could not be found in the graph.
  • ParameterMappingException - Thrown when grapefruit failed to convert a certain argument from a string to whatever type it needed to be converted to. This happens if the input is invalid (i.e. the string "hello" has to be converted to a number, which is obviously not possible), but not if grapefruit doesn't know the type of that specific parameter. In the latter case, the command won't be registered at all.
  • UnrecognizedFlagException - This is thrown, when an unknown flag appears in the command arguments (for instance --flag is specified, but it's not an actual parameter of the command).

Registering Custom Handlers

It's really easy, believe me :)

final CommandDispatcher<CommandSource> dispatcher = //...
dispatcher.registerHandler(CommandSyntaxException.class, (source, commandLine, ex) -> /* do whatever you wish*/);

The only caveat here is that only subclasses of CommandException are supported by this kind of exception handling.