Discord.NET-获取在命令中引发哪种类型的异常

我认为,如果说一个人没有运行命令的正确权限,或者有一个冷却时间之类的东西,而不是仅仅每隔...一次就处理一次,则抛出异常会更容易。因此,我创建了自己的异常,但问题是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

        }


SMILET
浏览 145回答 1
1回答

弑天下

您可能不想在此处使用try / catch,因为您不必要地抛出了自己的异常,然后在之后直接捕获它。您可以将错误处理放入case CommandError.Exception。如果您想更多地了解导致错误的异常,请执行以下操作:由于您正在调用该ExecuteAsync函数,因此“结果”可能不仅是类型IResult,而且是ExecuteResult类型。这意味着将存在一个属性“ Exception”,该属性存储“出了什么问题”。case CommandError.Exception:    if (result is ExecuteResult execResult)    {        //you can now access execResult.Exception to see what happened    }break;
打开App,查看更多内容
随时随地看视频慕课网APP