猿问

Python - 来自两个相似函数的不同类型的错误

我有一个 Discord 机器人,可以根据命令在语音通道中播放音频文件。当该文件不存在时,我想通过处理它try / except- 问题是,


discord.FFmpegPCMAudio只是res/mp3s/asff.mp3: No such file or directory直接打印到控制台,而不是触发该except部分。


但我不明白的是:当我放入open(filename, r)同一函数时,它会正确返回[Errno 2] No such file or directory并触发我的except处理。


为什么同一位置的两个函数都尝试访问文件会给我的异常处理带来两个不同的结果,我该如何防止它?我的第一个简单的解决方案是os.path.exist()在调用函数之前手动执行,但我想知道为什么我首先会遇到这个问题。


这大致就是我的代码的样子,当然不能直接复制,因为你需要一个正在运行的不和谐机器人......


async def playAudioFile(message, audiofile, volume):

    with open('res/mp3s/{}.mp3'.format(audiofile.lower()), "r") as f:

        print(f.read())            #returns error towards my exception handler as expected


    if volume is None:

        voice_channel = message.author.voice.channel

        vc = await voice_channel.connect()

        vc.play(discord.FFmpegPCMAudio('res/mp3s/{}.mp3'.format(audiofile.lower())))    #prints directly into console, ignores my exception handler

        while vc.is_playing() == True:

            pass

        else:

            for x in bot.voice_clients:

                if (x.guild == message.guild):

                    await x.disconnect()



@commands.command()

async def play(self, ctx, argument, volume):

    try:

        await playAudioFile(audiofile=argument, message=ctx.message, volume=volume):

    except Exception as e:

        print("Ooops!" + str(e))


慕慕森
浏览 103回答 1
1回答

函数式编程

Discord 的默认行为是捕获所有异常,并将它们打印到控制台。但是,您可以通过使用创建自己的错误处理程序来覆盖默认错误处理程序on_command_error()。下面是一个自定义错误处理程序的基本示例,可帮助您入门。这样,您可以使用 an 检查捕获的异常的类型if-statement(以不同的方式处理每种类型的异常),并对其执行您想要的操作。
随时随地看视频慕课网APP

相关分类

Python
我要回答