我有一個(gè) Discord 機(jī)器人,可以根據(jù)命令在語(yǔ)音通道中播放音頻文件。當(dāng)該文件不存在時(shí),我想通過(guò)處理它try / except- 問(wèn)題是,discord.FFmpegPCMAudio只是res/mp3s/asff.mp3: No such file or directory直接打印到控制臺(tái),而不是觸發(fā)該except部分。但我不明白的是:當(dāng)我放入open(filename, r)同一函數(shù)時(shí),它會(huì)正確返回[Errno 2] No such file or directory并觸發(fā)我的except處理。為什么同一位置的兩個(gè)函數(shù)都嘗試訪問(wèn)文件會(huì)給我的異常處理帶來(lái)兩個(gè)不同的結(jié)果,我該如何防止它?我的第一個(gè)簡(jiǎn)單的解決方案是os.path.exist()在調(diào)用函數(shù)之前手動(dòng)執(zhí)行,但我想知道為什么我首先會(huì)遇到這個(gè)問(wèn)題。這大致就是我的代碼的樣子,當(dāng)然不能直接復(fù)制,因?yàn)槟阈枰粋€(gè)正在運(yùn)行的不和諧機(jī)器人......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))
1 回答

函數(shù)式編程
TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊
Discord 的默認(rèn)行為是捕獲所有異常,并將它們打印到控制臺(tái)。但是,您可以通過(guò)使用創(chuàng)建自己的錯(cuò)誤處理程序來(lái)覆蓋默認(rèn)錯(cuò)誤處理程序on_command_error()
。下面是一個(gè)自定義錯(cuò)誤處理程序的基本示例,可幫助您入門(mén)。
這樣,您可以使用 an 檢查捕獲的異常的類型if-statement
(以不同的方式處理每種類型的異常),并對(duì)其執(zhí)行您想要的操作。
添加回答
舉報(bào)
0/150
提交
取消