【问题标题】:Can't catch exception for an invalid image URL in discord.py无法捕获 discord.py 中无效图像 URL 的异常
【发布时间】:2019-12-31 22:29:22
【问题描述】:

我在 discord.py 中为我的 Discord 机器人创建了一个 embed_test 命令,并且我正在尝试使用 try ... except 子句让机器人说“无效的 url”,如果给定的图像 URL 无效:

@commands.command()
async def embed_test(sefl, ctx, *, image_url):

    embed = discord.Embed(title = 'Very nice title', description = 'Interesting description', color = 0x00A900)

    if (image_url[0], image_url[-1]) == ('"', '"'):

        try: embed.set_image(url = image_url[1:])

        except Exception: await ctx.send('invalid image url')

    else: await ctx.send('please enter the url in "quotation marks"')

    await ctx.send(embed = embed)

当子句不在 if ... else 语句中时,这非常有效,但是,如图所示,我还想确保用户在引号中输入他们的 URL。问题是,当我使用引号中的无效 URL 运行命令时,我得到:

Command raised an exception: HTTPException: 400 BAD REQUEST (error code: 50035): Invalid Form Body
In embed.image.url: Not a well formed URL.

在我的控制台中,即使我试图在我的程序中捕获异常。

【问题讨论】:

  • 您确实应该在此处添加代码而不是 png 链接。这样人们就可以试一试。

标签: python exception bots discord.py


【解决方案1】:

这是因为您在 image_url[1:] 中包含了右引号。
你应该改用image_url[1:-1] 之类的东西。

您的错误处理不起作用的原因是因为在出错时没有设置图像 URL。 discord.py 本身不检查 URL。正如完整的回溯应该向您指出的那样,当您尝试发送嵌入时会发生此错误。它被发送到 Discord 的 API,当 Discord 尝试使用该 URL 时,请求会返回错误代码。

此外,您应该尽量避免捕获所有异常,而不是您正在处理的特定异常。否则,您可能会屏蔽其他异常,从而使调试代码变得更加困难。
请参阅https://wiki.python.org/moin/HandlingExceptionshttps://docs.python.org/3/tutorial/errors.html,了解有关避免此类错误处理的不良做法的更多详细信息。

【讨论】:

    猜你喜欢
    • 2019-10-30
    • 2010-10-29
    • 1970-01-01
    • 2011-04-19
    • 2021-10-09
    • 1970-01-01
    • 2021-09-17
    • 2021-10-03
    相关资源
    最近更新 更多