zh_cn:tutorial:command_exceptions
This is an old revision of the document!
命令异常
Brigadier支持命令异常,这些异常可用于结束命令,例如参数未正确解析或命令未能执行,以及更丰富的错误细节。
Brigadier的所有异常都基于“CommandSyntaxException”。Brigadier提供的两种主要异常类型是动态和一般,其中必须“create()“异常才能引发异常。这些异常还允许您使用”createWithContext(ImmutableStringReader)“指定引发异常的上下文,该上下文将生成错误消息指向命令行中出现错误的位置。
下面是一个抛硬币命令,用于显示使用中的异常示例。
对于1.18及以下:
dispatcher.register(literal("coinflip") .executes(ctx -> { if(random.nextBoolean()) { // If heads succeed. ctx.getSource().sendMessage(Text.translatable("coin.flip.heads")) return Command.SINGLE_SUCCESS; } throw new SimpleCommandExceptionType(new TranslatableText("coin.flip.tails")).create(); // Oh no tails, you lose. }));
异常不只有一种,Brigadier还提供了动态异常,能为上下文提供额外的参数。
DynamicCommandExceptionType used_name = new DynamicCommandExceptionType(name -> { });
1.19及以上:
dispatcher.register(literal("coinflip") .executes(ctx -> { if(random.nextBoolean()) { // If heads succeed. ctx.getSource().sendMessage(Text.translatable("coin.flip.heads")) return Command.SINGLE_SUCCESS; } throw new SimpleCommandExceptionType(Text.translatable("coin.flip.tails")).create(); // Oh no tails, you lose. }));
异常不只有一种,Brigadier还提供了动态异常,能为上下文提供额外的参数。
DynamicCommandExceptionType used_name = new DynamicCommandExceptionType(name -> { });
还有更多的动态异常类型,每种类型都考虑了不同数量的参数(“Dynamic2CommandExceptionType”、“Dynamic3CommandExcessionType”、”“Dynamic4CommandExcitionType”“、”“Dynamic NCommandExclusionType”“)。你应该记住,动态异常将对象作为参数,因此你可能必须强制转换参数以供使用。
zh_cn/tutorial/command_exceptions.1672636100.txt.gz · Last modified: 2023/01/02 05:08 by lei64