簡體   English   中英

Discord.JS catch function 沒有抓到錯誤

[英]Discord.JS catch function not catching errors

我正在嘗試制作一個命令,讓用戶直接發送命令列表,但如果它無法發送它們,它會在頻道中發送一條消息,告訴用戶檢查他們的隱私設置以允許服務器成員私信他們。

但是,當我嘗試使用“catch”function 時,它要么吐出錯誤,要么沒有捕獲命令。 這是我當前的代碼。

if(cmd=== `${prefix}test`){
    try {
    message.author.send("test")
    }
    catch(error){
    message.channel.send("Unable to send")
    }
    
  }

這不起作用,如果我將其更改為

if(cmd=== `${prefix}test`){
    try {
    message.author.send("test")
    }.catch(error){
    message.channel.send("Unable to send")
    }
    
  }

它說“ SyntaxError: Missing catch or finally after try

我嘗試了很多解決方案並查看了其他幾個 stackoverflow 問題,但我找不到解決方案。 如果需要更多詳細信息,請發表評論,我會盡力回答。

這是因為message.author.send()是一個異步 function; 它將始終返回 promise。這意味着send()返回並退出try塊,因此您的catch塊將永遠不會運行。

嘗試先使用await關鍵字等待send()解析(或拒絕):

if (cmd === `${prefix}test`) {
  try {
    await message.author.send('test');
  } catch (error) {
    message.channel.send('Unable to send');
  }
}

暫無
暫無

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

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