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

Discord.NET - Get Which Type of Exception was Thrown in Command

我认为如果说一个人没有 运行 命令的正确权限,或者有冷却时间等等,而不是仅仅处理那个 每...单次...时间。所以我自己做了例外,但问题是 CommandService.ExecuteAsync().Error only returns the 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
        }

你可能不想在那里使用 try/catch,因为你会不必要地抛出你自己的异常,然后直接捕获它。您可以将错误处理放入 case CommandError.Exception.

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

由于您正在调用 ExecuteAsync 函数,因此 "result" 可能不仅属于 IResult 类型,而且属于 ExecuteResult 类型。这意味着有一个 属性 "Exception" 存储 "what went wrong".

case CommandError.Exception:
    if (result is ExecuteResult execResult)
    {
        //you can now access execResult.Exception to see what happened
    }

break;