NodeJS 开关正常执行,然后抛出错误

cyej8jka  于 2022-12-29  发布在  Node.js
关注(0)|答案(1)|浏览(146)

这有点奇怪。我写了代码来检查不一致的消息内容(msg.content)是否以前缀(例如"! add-badword foo")开头,并返回没有前缀的字符串。然后switch应该将其与可用命令进行比较,并执行一些代码。问题是,所有这些都正常工作,它按照它应该的方式执行代码,然后,在switch完全执行后,它抛出错误。
我该怎么做才能修好它?
返回不带前缀的字符串的函数:

async function isCommand (msg){
    let q = await serverConfig.findOne({_id: msg.guildId+""},{prefix:1})
    if(msg.content.indexOf(q.prefix)==0){
        return msg.content.slice(1)
    }else{
        return false
    }
}

有问题的开关:

const command = await isCommand(msg);
switch(command.split(' ')[0]){
    default: 
        msg.reply('Command not recognized');
        break;
    case 'set-prefix':
        msg.reply('Prefix changed to ' + command.split(' ')[1]);
        break;
    case 'ignore-channel':
        msg.reply('Ignoring channel ' + command.split(' ')[1]);
        break;
    case 'unignore-channel':
        msg.reply('Channel ' + command.split(' ')[1] + ' unignored');
        break;
    case 'ignore-badword':
        msg.reply('Ignoring word ' + command.split(' ')[1]);
        break;
    case 'unignore-badword':
        msg.reply('Word ' + command.split(' ')[1] + ' unignored');
        break;
    case 'add-badword':
        msg.reply('Added word ' + command.split(' ')[1] + ' to bad words');
        break;
    case 'remove-badword':
        msg.reply('Removed word ' + command.split(' ')[1] + ' from bad words');
        break;    
}

(Not?)工作代码对不一致的影响:

错误:

node:events:491
      throw er; // Unhandled 'error' event
      ^

TypeError: command.split is not a function
    at Client.<anonymous> (C:\xampp\htdocs\GitHub\forgotten-droid\index.js:56:29)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
Emitted 'error' event on Client instance at:
    at emitUnhandledRejectionOrErr (node:events:394:10)
    at processTicksAndRejections (node:internal/process/task_queues:85:21)
jjjwad0x

jjjwad0x1#

好了,我找到了解决方案。代码也被bot的消息触发了,因为它不包含前缀,command变量被设置为false。因此,开关失败,因为false没有**split()**函数。所以我将有问题的开关嵌套如下:

if (command) {
    //switch here
}

相关问题