如何使 python 执行异常,而不是忽略它 (discord.py)

How to make python execute exception, instead of ignoring it (discord.py)

所以,我正在编写一个脚本,允许我的 discord 机器人在发出命令后使用 lyricgenius API 来 return 歌词。但是,每当我故意输入乱码以使机器人无法找到歌词并执行 AttributeError 异常块中的代码时,控制台都会显示异常被忽略。我正在使用 discord.py 版本 1.01。有任何想法吗?提前致谢

def fetch_lyrics(array):
    song = genius.search_song(title=array[0],artist=array[1])
    return song.lyrics

@client.event
async def on_message(message):
    if message.content.startswith("hello"):
        await message.channel.send("hello")

    if message.content.startswith("$lyrics"):
        global lyrics
        global searchstring
        pre_search_array =  message.content.split()
        del pre_search_array[0]

        for z in pre_search_array:
            searchstring += z+" "

        search_array = searchstring.split(",")

        if len(fetch_lyrics(search_array)) > 2000:
            pass

        else :
            try:
                await message.channel.send(fetch_lyrics(search_array))
            except AttributeError:
                await message.channel.send("Could not find the song")

        #resets the list
        searchstring = ""
        pre_search_array.clear()
        search_array.clear()


Error Message:
Ignoring exception in on_message
Traceback (most recent call last):
  File "/Users/kevinhadinata/Desktop/pythonProject2/venv/lib/python3.7/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "/Users/kevinhadinata/Desktop/pythonProject2/main.py", line 38, in on_message
    if len(fetch_lyrics(search_array)) > 2000:
  File "/Users/kevinhadinata/Desktop/pythonProject2/main.py", line 16, in fetch_lyrics
    return song.lyrics
AttributeError: 'NoneType' object has no attribute 'lyrics'
Fatal read error on socket transport
protocol: <asyncio.sslproto.SSLProtocol object at 0x102ae0908>
transport: <_SelectorSocketTransport fd=11 read=polling write=<idle, bufsize=0>>
Traceback (most recent call last):
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/asyncio/selector_events.py", line 801, in _read_ready__data_received
    data = self._sock.recv(self.max_size)
TimeoutError: [Errno 60] Operation timed out

您正在 len(fetch_lyrics(search_array)) > 2000: 中使用 fetch_lyrics(导致错误),您必须捕获该错误。直接方法是将其移至 try and except。

try:
   if len(fetch_lyrics(search_array)) > 2000:
            pass
except AttributeError:
   print('not a valid song')

您还可以在 fetch_lyrics 中引发自定义错误并捕获它。