zh_cn:tutorial:command_exceptions
This is an old revision of the document!
命令异常
Brigadier 支持命令异常,这些异常可用于结束命令,例如参数未正确解析或命令未能执行,以及更丰富的错误细节。
Brigadier 的所有异常都基于 CommandSyntaxException。Brigadier 提供的两种主要的异常类型是动态(Dynamic)和一般(Simple),你需要用 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. }));
动态
DynamicCommandExceptionType used_name = new DynamicCommandExceptionType(name -> { });
还有更多的动态异常类型,每种类型都考虑了不同数量的参数(“Dynamic2CommandExceptionType”、“Dynamic3CommandExcessionType”、”“Dynamic4CommandExcitionType”“、”“Dynamic NCommandExclusionType”“)。你应该记住,动态异常将对象作为参数,因此你可能必须强制转换参数以供使用。
zh_cn/tutorial/command_exceptions.1672636579.txt.gz · Last modified: 2023/01/02 05:16 by lei64