簡體   English   中英

不斷給我 Unhandled Promise 拒絕警告,我無法發現錯誤

[英]Keeps giving me Unhandled Promise Rejection Warning and I'm unable to spot the error

這是我的代碼,順便說一句,我有一個命令處理程序。

const Discord = require('discord.js');
const bot = new Discord.Client();
const token = 'hidden';
const sqlite = require('sqlite3').verbose();
const dayno = '0';
const PREFIX = '$';
const fs = require('fs');



bot.on('message', (message) => { 
    let userid = message.author.id;

if (message.author.bot || !message.content.startsWith(PREFIX)) return;
    if(message.author.bot)return;
    let db = new sqlite.Database('./database.db', sqlite.OPEN_READWRITE );


            bot.commands = new Discord.Collection();

            const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
            for(const file of commandFiles){
                const command = require(`./commands/${file}`);

                bot.commands.set(command.name, command);


            if (message.author.bot || !message.content.startsWith(PREFIX)) 
            return;

            let args = message.content.substring(PREFIX.length).split(" ");
        switch(args[0]){

            case 'help':

                bot.commands.get('help').execute(message, args);    
            break;

            case 'getreports':

                if(message.member.roles.cache.find(r => r.name
                    === "Developers")) return message.channel('You are not authorized to use this command.')
                    bot.commands.get('getreports').execute(message, args);         

            break;

            case 'getreportsof':


                if(message.member.roles.cache.find(r => r.name
                    === "Developer")){
                    bot.commands.get('getreportsof').execute(message, args);   
                }else{

                message.reply('You are not authorized to use this command.')

                }    

            break;



        };

    };


});

bot.on('ready', () =>{
    console.log('Duncan Online');
    bot.user.setActivity('$help', {type: "LISTENING"}).catch(console.error);
    let db = new sqlite.Database('./database.db', sqlite.OPEN_READWRITE | sqlite.OPEN_CREATE)
    db.run('CREATE TABLE IF NOT EXISTS data(userid INTEGER NOT NULL, reports INTEGER NOT NULL)')
});


bot.login(token);

這是錯誤:

(node:12456) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message
    at RequestHandler.execute (C:\Users\HP_Omen\Desktop\Testing\node_modules\discord.js\src\rest\RequestHandler.js:170:25)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:12456) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a 
catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag 
`--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:12456) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我在您提供的代碼中看不到任何會直接導致錯誤的內容。 這很可能來自您的命令。

對於每個 switch 案例,使用如下內容:

bot.commands.get('help').execute(message, args).catch(console.error)

catch應該可以幫助您找到錯誤。 如果沒有,請將.catch(console.error)添加到您在命令中調用異步函數(返回承諾的函數)的任何位置。


我個人發現使用async函數和await而不是thencatch更容易和可讀,因此您也可以將代碼重構為如下所示:

// commands/help.js
module.exports = {
    name: 'help',
    async execute(message, args) {
        // note how I use await here 
        await message.channel.send('some useful help message');
    }
};

// your main file (probably index.js or something)
bot.on('message', async (message) => {
    try {
        // rest of code...
        switch (args[0]) {
            case 'help':
                // use await here as well so that the errors get caught
                await bot.commands.get('help').execute(message, args);
                break;
            // rest of commands
        }
    } catch (error) {
        // log all errors
        console.error(error)
    }
});

有關未處理的 promise 拒絕的更多信息,請參閱此答案

我忘了關閉這個:

            for(const file of commandFiles){
                const command = require(`./commands/${file}`);

                bot.commands.set(command.name, command);

它像這樣工作得很好:

        for(const file of commandFiles){
            const command = require(`./commands/${file}`);

            bot.commands.set(command.name, command);

}

無論如何,我感謝你的回答。

暫無
暫無

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

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