Discord.js解封命令报读取undefined的user属性错误
问题根因
你当前代码的报错点出在封禁列表取值的链式调用逻辑:
当传入的用户ID不在服务器封禁列表中时,getGuildBanList.get(unbanUserId)会直接返回undefined,此时你直接读取.user属性就会抛出Cannot read properties of undefined (reading 'user')错误,代码会直接进入外层catch块,完全跳过后续的if/else判断,因此未封禁用户的提示分支永远不会被触发。
修复方法
先判断封禁列表中是否存在对应用户的条目,再执行后续逻辑,不要在不确定值存在的情况下直接链式读取属性。
修复后的参考代码:
const unbanUserId = interaction.options.getString('user_id') try { const getGuildBanList = await interaction.guild.bans.fetch() // 先获取封禁条目,不直接取.user属性 const banEntry = getGuildBanList.get(unbanUserId) if (banEntry) { await interaction.guild.members.unban(unbanUserId) const unBannedEmbed = new MessageEmbed() .setColor('PURPLE') .setTitle('User unbanned') .setDescription(`Successfully unbanned <@!${unbanUserId}>`) return interaction.editReply({ embeds: [unBannedEmbed] }) } else { const notBanned = new MessageEmbed() .setColor('PURPLE') .setDescription(`The stated user is not banned.`) return interaction.editReply({ embeds: [notBanned] }) } } catch(e) { console.log(e) }
优化建议
不需要拉取全量封禁列表再匹配,可以直接调用interaction.guild.bans.fetch(unbanUserId)查询单个用户的封禁状态,减少接口请求的数据量,性能更好:
const unbanUserId = interaction.options.getString('user_id') try { // 直接查询单个用户封禁状态,不存在时会抛出明确的不存在错误 const banEntry = await interaction.guild.bans.fetch(unbanUserId) await interaction.guild.members.unban(unbanUserId) const unBannedEmbed = new MessageEmbed() .setColor('PURPLE') .setTitle('User unbanned') .setDescription(`Successfully unbanned <@!${unbanUserId}>`) return interaction.editReply({ embeds: [unBannedEmbed] }) } catch (e) { // 捕获到用户未被封禁的错误时返回对应提示 if (e.code === 10026) { // Discord API 未知封禁错误码 const notBanned = new MessageEmbed() .setColor('PURPLE') .setDescription(`The stated user is not banned.`) return interaction.editReply({ embeds: [notBanned] }) } console.log(e) }
内容的提问来源于stack exchange,提问作者Joel
相关产品推荐
相关产品推荐

