簡體   English   中英

為什么這個 try..catch 塊沒有捕捉到錯誤?

[英]Why does this try .. catch block not catch the error?

因此,我正在為我的 Discord 機器人和 Discord 角色層次結構和所有這些工作制定一個禁止命令,我認為如果被 ping 的用戶高於機器人,則 try...catch 塊會起作用。 這是我的代碼:

try {
    msg.mentions.members.first().ban()
} catch (error) {
    errorOccured = true
    let embed = new Discord.MessageEmbed()
    .setTitle("Error")
    .setDescription(`I do not have permissions to ban <@${msg.mentions.members.first().id}>.`)
    .setTimestamp()
    .setColor('RED')
    return msg.channel.send(embed)
}

這是我得到的錯誤:

UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions

現在,我的問題是,為什么這個 catch 塊沒有捕捉到錯誤? 如果我只是愚蠢,請解釋為什么以及如何解決這個問題。 謝謝!

快速編輯:我已經嘗試過使用process.on('unhandledRejection'....但由於某種原因,這也會發現以前的錯誤,我不知道如何解決這個問題。如果你有解決方案,更好::)

編輯 2:@TinNguyen 在評論中已修復,謝謝。 ps,@Bergur 的解決方案也可能是一個解決方案。 但我現在沒有時間測試它。

UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions

可以通過以下方式處理此警告:

guildMember.ban({ days: 7, reason: 'They deserved it' })
    .then(console.log)
    .catch(console.error);

如問題所示的一般 try catch 塊不會處理該警告。

fetch() 返回一個 Promise,這意味着有兩個執行路徑,一個延遲。 您的一般 try/catch 捕獲“主”線程。 當“延遲”的 Promise 執行路徑返回其結果時,該 try/catch 塊早已不復存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM