User Tools

Site Tools


tutorial:command_exceptions

This is an old revision of the document!


Exceptions

Brigadier supports command exceptions which can be used to end a command such as if an argument didn't parse properly or the command failed to execute, as well as including richer details of the failure.

All the exceptions from Brigadier are based on the CommandSyntaxException. The two main types of exceptions Brigadier provides are Dynamic and Simple exception types, of which you must create() the exception to throw it. These exceptions also allow you to specify the context in which the exception was thrown using createWithContext(ImmutableStringReader), which builds the error message to point to where on the inputted command line the error occured.

Below is a coin flip command to show an example of exceptions in use.

  1. dispatcher.register(literal("coinflip")
  2. .executes(ctx -> {
  3. Random random = new Random();
  4.  
  5. if(random.nextBoolean()) { // If heads succeed.
  6. ctx.getSource().sendMessage(Text.translatable("coin.flip.heads"))
  7. return Command.SINGLE_SUCCESS;
  8. }
  9.  
  10. throw new SimpleCommandExceptionType(Text.translatable("coin.flip.tails")).create(); // Oh no tails, you lose.
  11. }));

Though you are not just limited to a single type of exception as Brigadier also supplies Dynamic exceptions which take additional parameters for context.

  1. DynamicCommandExceptionType used_name = new DynamicCommandExceptionType(name -> {
  2. return Text.literal("The name: " + (String) name + " has been used");
  3. });

There are more Dynamic exception types which each take a different amount of arguments into account (Dynamic2CommandExceptionType, Dynamic3CommandExceptionType, Dynamic4CommandExceptionType, DynamicNCommandExceptionType). You should remember that the Dynamic exceptions takes an object as an argument so you may have to cast the argument for your use.

tutorial/command_exceptions.1659925012.txt.gz · Last modified: 2022/08/08 02:16 by solidblock