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

Node.js Promise链内部错误排查:discord.PostTournament异常

排查Node.js Promise链中Discord Webhook调用的异常问题

从你给出的错误栈和代码来看,这个TypeError: String is not a function看似诡异,本质是未处理的Promise拒绝触发的底层警告异常,结合你的代码细节,我整理了几个关键排查和修复方向:

1. 修复导出函数的Promise返回逻辑,让错误能被外部捕获

你在discord.js里的导出函数有个明显问题:作为async函数,它没有返回内部PostTournament调用的Promise,且内部catch仅打印错误却没有传递给外部Promise链。这会导致外部链无法感知异步操作的状态,触发Node.js未处理Promise拒绝警告,最终引发那个奇怪的String相关错误。

修改导出函数代码:

module.exports.PostTournament = async function (pPosts) {
  try {
    // 等待内部函数执行完成
    await PostTournament(pPosts);
  } catch (err) {
    console.log("内部错误:", err);
    // 必须重新抛出错误,让外部Promise链的catch能捕获到
    throw err;
  }
}

或者更简洁的写法:

module.exports.PostTournament = function (pPosts) {
  // 直接返回Promise,让外部链跟踪状态
  return PostTournament(pPosts)
    .catch(err => {
      console.log("内部错误:", err);
      throw err;
    });
}

2. 排查是否全局覆盖了String构造函数

错误栈的报错点是process.emitWarning内部的String(type || 'Warning'),这说明全局String构造函数被意外改成了非函数类型(比如字符串)。请检查所有代码文件,看有没有类似下面的错误赋值:

// 这种错误会彻底破坏内置的String构造函数
String = "some value";

如果找到这类代码,立刻删除或修正。

3. 优化Discord WebhookClient的使用,避免资源泄漏

你的PostTournament函数每次循环都新建WebhookClient,既没必要还可能导致资源泄漏、触发Discord API调用限制。把客户端创建移到循环外面:

async function PostTournament (pPosts) {
  try {
    // 只创建一次WebhookClient
    const client = new Discord.WebhookClient(webhookID, webhookToken);
    client.name = "Network of Darkness - Admin";
    
    for (let pPost of pPosts) {
      // 注意:Discord.js v12及以上版本需把RichEmbed改为MessageEmbed
      const embed = new Discord.RichEmbed()
        .setTitle("New Tournament")
        .setURL(pPost.link)
        .setImage(pPost.picture)
        .setDescription(pPost.message)
        .setColor("b23aee");
      await client.send(`:loudspeaker: <@&${roleid}>`, embed);
    }
    // 使用完后销毁客户端,释放资源
    client.destroy();
  } catch (error) {
    console.log(error);
    // 抛出错误让上层处理
    throw error;
  }
}

4. 验证Promise链的错误捕获流程

修复完成后,重新运行代码,此时外部Promise链的.catch应该能正确捕获discord.PostTournament内部的错误,而非触发底层process警告。你可以在外部catch里打印更详细的错误信息:

facebook.GetDiscordPosts(5)
 .then(posts => TournamentsFilter(posts))
 .then(tournaments => ToDataFile(tournaments))
 .then(pPosts => discord.PostTournament(pPosts))
 .then(r => console.log("Done!"))
 .catch(err => console.log("全局捕获错误:", err.stack)) // 打印完整错误栈

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:25:19