discord.js中try catch无法捕获Embed非法URL报错问题求助
问题原因
- 你当前的
try/catch只能捕获同步执行代码抛出的错误,而message.channel.send()是异步方法,返回Promise对象,它内部抛出的错误属于异步错误,同步的try/catch无法捕获,因此会导致进程直接崩溃。 - 你的代码本身还存在语法错误:
console.log(error)后面直接链式调用.setTitle()是无效的,console.log返回值为undefined,调用undefined.setTitle()会额外抛出错误。
解决方案
方法1:使用async/await改写逻辑,让try/catch可以捕获异步错误
你只需要给外层处理函数加上async关键字,给异步的send方法加上await即可,修正后的代码如下:
// 注意!要给当前这个事件处理函数加async关键字,示例: // client.on('messageCreate', async (message) => { 这里必须加async try { let json = message.content.split(" ") json.shift() // 移除命令前缀部分,保留JSON内容 let data = json.join(" ") let embedjson = new Discord.MessageEmbed(JSON.parse(data)) // 给send方法加await await message.channel.send({ embeds: [embedjson]}) } catch (error) { console.log(error) // 链式调用要接在MessageEmbed实例后面 let errorembed = new Discord.MessageEmbed() .setTitle('Error!') .setDescription(`Something went wrong! There are a few possible issues:\n1. You tried to put text in a link option (Like putting 'hello' in the image option, or 'never gonna give you up' in the thumbnail option.)\n2. Something else\nI'll attatch the error below:`) .addField('Error Message', error.toString()) await message.channel.send({ embeds: [errorembed]}) }
方法2:使用Promise的.catch()方法单独捕获send的错误
如果你不想改异步写法,也可以直接给send方法链式调用.catch()处理错误:
try { let json = message.content.split(" ") json.shift() let data = json.join(" ") let embedjson = new Discord.MessageEmbed(JSON.parse(data)) message.channel.send({ embeds: [embedjson]}) .catch(error => { console.log(error) let errorembed = new Discord.MessageEmbed() .setTitle('Error!') .setDescription(`Something went wrong! There are a few possible issues:\n1. You tried to put text in a link option (Like putting 'hello' in the image option, or 'never gonna give you up' in the thumbnail option.)\n2. Something else\nI'll attatch the error below:`) .addField('Error Message', error.toString()) message.channel.send({ embeds: [errorembed]}) }) } catch (error) { // 这里捕获JSON解析、Embed构造阶段的同步错误 console.log(error) let errorembed = new Discord.MessageEmbed() .setTitle('Error!') .setDescription(`Something went wrong! There are a few possible issues:\n1. Invalid JSON format\n2. Incorrect Embed field structure\nI'll attatch the error below:`) .addField('Error Message', error.toString()) message.channel.send({ embeds: [errorembed]}) }
额外优化建议
你可以在构造Embed之后、发送之前提前校验图片、缩略图等字段的URL格式,提前拦截不符合要求的输入,不需要等到发送时才抛出错误:
- 校验Embed的
image.url、thumbnail.url、author.iconURL、footer.iconURL等字段是否以http://或https://开头 - 校验不通过直接返回错误提示,不需要执行发送逻辑
内容的提问来源于stack exchange,提问作者johng3587
相关产品推荐
相关产品推荐

