Discord.NET - 获取命令中抛出哪种类型的异常

问题描述 投票:0回答:1

我认为,如果说一个人没有正确的权限来运行命令,或者有冷却时间,或者其他什么,抛出异常会更容易,而不是仅仅处理每次......单次......时间。所以我自己创建了异常,但问题是 CommandService.ExecuteAsync().Error 只返回 CommandError.Exception,无法(据我所知)找出抛出了哪种类型的异常。

我的代码如下:

try { var result = await _service.ExecuteAsync(context, argPos); if (!result.IsSuccess) switch (result.Error) { case CommandError.BadArgCount: await context.Channel.SendMessageAsync("Bad argument count."); break; case CommandError.UnknownCommand: break; case CommandError.Exception: // This is what happens instead of the catch block. break; default: await context.Channel.SendMessageAsync($"You 👏👏 Broke 👏👏 It ({result.ErrorReason})"); break; } } catch (Exceptions.GameCommandNotReadyException e) { // The code never gets here because of the CommandError.Exception }
    
c# exception bots discord discord.net
1个回答
1
投票
您可能不想在那里使用 try/catch,因为您会不必要地抛出自己的异常,然后直接捕获它。您可以将错误处理放入

case CommandError.Exception

如果您想了解更多有关导致错误的异常:

由于您正在调用

ExecuteAsync

 函数,因此“结果”很可能不仅是 
IResult
 类型,而且是 
ExecuteResult 类型。这意味着有一个属性“异常”存储“出了什么问题”。

case CommandError.Exception: if (result is ExecuteResult execResult) { //you can now access execResult.Exception to see what happened } break;
    
© www.soinside.com 2019 - 2024. All rights reserved.