Skip to content

Command Fail

Gabriel Souza edited this page Aug 14, 2020 · 5 revisions

Command fail is similar to a return but with a Message to a Player or with a code execution lambda.

myPlugin.simpleCommand("warp") {
  val player = sender as? Player ?: fail("Please, use this command just in game")
  val arg0 = args.getOrNull(0) ?: fail("Please add the warp name")
  val warp = warpManager.findWarp(arg0) ?: fail("This warp was not found")

  warp.teleport(player)
}

How it works

The fail extension throws an exception called CommandFailException that is catch by the Command framework. This means that when you call fail will block your code, but the Exception will be treated by the CommandDSL sending message to the Player if was one to send.

Where it can help you

  • Null safety: val player: Player = sender as? Player ?: fail("Please, use this command just in game")
  • Small if statements: if(!player.hasPermission("myplugin.permission")) fail("You don't have permission")
  • And much more.

In arguments

This is usage on Command Arguments for not continue your code if the Player pass an invalid argument, making your code cleaner.

The CommandFailException has a boolean argument argMissing usage by the optional argument block for handle if the CommandFailException was throw because of an argument missing by the player. This is something that I will not use, but, is good to know how it works.

More about Command Arguments.

Error Handling

We can also handle any type of exception that can occur in your plugin by using the errorHandler callback. The handler will be set to all child/sub commands as well.

command("test") {
  errorHandler { exception ->
     when(exception) {
        is KitNotFoundException -> sender.msg("&cThe introduced kit ${exception.kit} was not found.".translateColor())
        else -> defaultErrorHandling(exception)
     }
  }
}
defaultErrorHandling

By default, KotlinBukkitAPI provide an error handler similar to Bukkit. It will send a message to the player An internal error occurred whilst executing this command and when hover the message will show the full stack trace of the error.

Clone this wiki locally