You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.js机器人join语音频道命令执行报错如何添加捕获处理逻辑?

解决方案

membervc.join() 本身是异步方法,会返回Promise对象,执行出错时会抛出拒绝状态的Promise,没有做错误处理就会触发未捕获异常导致机器人崩溃。你可以直接配合函数已有的async声明,用try/catch + await的方式捕获异常,实现需求的报错提示。

修改后的完整代码

module.exports.run = async (client, message, args) => {
  let membervc = message.member.voice.channel;
  let botvc = message.guild.me.voice.channel;
  // 原代码的message.send为笔误,修正为message.channel.send
  if(!membervc) return message.channel.send('You need to join a voice channel first.');
  if(botvc){
      if(!(botvc.members.size - 1)) return message.reply(`I am already on ${botvc}`);
      if(membervc.id == botvc.id) return message.reply('We are already on the same voice channel.');
  };
  try {
    // 等待加入操作执行完成,出错会进入catch块
    await membervc.join();
  } catch (err) {
    // 捕获错误后返回提示,err.message为具体错误原因
    return message.reply(`I could not join the channel, "${err.message}"`);
  }
}

补充说明

  • 捕获到的错误对象的message属性会返回具体错误原因,常见场景包括机器人无加入语音频道权限、频道人数已满、语音服务器连接超时等,都可以正常返回给用户
  • 如果你使用的是discord.js v14及以上版本,语音功能已经拆分到独立的@discordjs/voice包,加入逻辑需要调整为使用joinVoiceChannel方法,错误捕获逻辑同理用try/catch包裹即可
  • 原有代码中的message.send属于笔误,正确写法为message.channel.send,否则会触发方法不存在的运行时报错

内容的提问来源于stack exchange,提问作者Bimo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 03:39:03