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

运行Discord.js+Axios足球比分Webhook代码时无报错却异常终止

程序无报错自行终止的原因分析

问题描述

我编写了一段基于Discord.js和Axios的代码,用于通过Discord Webhook发送足球赛事信息,并实时更新进球及点球比分。但点击运行后程序自行终止,控制台未输出任何报错信息。已尝试添加console.log语句排查问题,但未获取到有效线索。使用的数据源为football-data.org API,相关代码如下:

const axios = require('axios');
const { WebhookClient, EmbedBuilder } = require('discord.js');

console.log("Teste iniciado");

const apiKey = process.env['API_KEY'];
const leagues = [
  {
    id: '2002',
    name: 'Bundesliga',
    thumbnail: 'https://upload.wikimedia.org/wikipedia/pt/f/f9/Bundesliga_logo_%282017%29.png'
  }
];

async function getLiveScore(league) {
  console.log("Função getLiveScore iniciada");
  try {
    const response = await axios.get(`https://api.football-data.org/v4/competitions/${league.id}/matches`,
      {
        headers: {
          'X-Auth-Token': apiKey,
        }
      }).catch(function(error) {
        if (error.response) {
          console.log(error.response.data);
          console.log(error.response.status);
          console.log(error.response.headers);
        }
      });

    console.log("Resposta da API obtida com sucesso");

    const liveMatches = response.data.matches.filter(match => match.status === 'LIVE')

    const embed = new EmbedBuilder()
      .setTitle(`Placar ao vivo - ${league.name}`)
      .setColor('#0099ff')
      .setThumbnail(league.thumbnail);

    liveMatches.forEach(match => {
      let score = `${match.score.fullTime.homeTeam} x ${match.score.fullTime.awayTeam}`;
      if (match.score.penalties) {
        score += `\nPênaltis: ${match.score.penalties.homeTeam} x ${match.score.penalties.awayTeam}`;
      }
      embed.addFields(`${match.homeTeam.name} x ${match.awayTeam.name}`, `${score}`, true);

      if (match.score.goalsHomeTeam) {
        match.score.goalsHomeTeam.forEach(goal => {
          embed.addFields(`${match.homeTeam.name} gol`, `${goal.minute} - ${goal.scorer.name}`, true);
        });
      }
    });

    console.log("Função getLiveScore concluída com sucesso");
    return embed;
  } catch (error) {
    console.error(error);
  }
}
let resultado;
let esperado;
if (resultado === esperado) {
  console.log("resultado esperado obtido");
} else {
  console.error("resultado não é o esperado:", resultado);
}
module.exports = async (res) => {
  console.log("Função principal iniciada");
  const discordWebhookUrl = process.env['WEBHOOK_URL'];

  const client = new WebhookClient({ url: discordWebhookUrl });

  const promises = leagues.map(league => getLiveScore(league));
  const liveScores = await Promise.all(promises);

  liveScores.forEach(liveScore => {
    client.send({ embeds: [liveScore] });
  });

  res.status(200).send('Live scores sent.');
};

可能的原因

  • 主逻辑函数未被执行:代码最后导出了一个异步函数,但如果这是普通Node.js脚本(而非云函数/服务器路由),导出的函数不会自动触发执行。程序只会运行到module.exports语句就结束,主函数内的console.log("Função principal iniciada")根本不会被调用,自然看不到后续逻辑的输出。

  • 环境变量未正确加载:代码中使用process.env['API_KEY']和process.env['WEBHOOK_URL']获取环境变量,但如果没有安装并配置dotenv包(未在代码开头添加require('dotenv').config()),这些变量会是undefined。如果主函数执行,API请求会因缺少合法密钥失败,但当前主函数没运行,所以看不到报错。

  • Axios错误处理逻辑缺陷:axios.get后附加的.catch会捕获请求错误,但未返回任何值,导致response变为undefined。后续访问response.data会抛出TypeError,但该错误会被外层try/catch捕获并打印。不过由于主函数未执行,这个错误也不会出现。

  • Discord.js Embed字段格式错误:Discord.js v14的EmbedBuilder.addFields要求传入字段对象(如{ name: '标题', value: '内容', inline: true }),但代码中直接传入三个参数,这会导致方法调用失败。若主函数执行,此处会抛出错误,但当前未执行主逻辑,所以无报错输出。

  • 异步操作未处理完成:client.send是异步Promise操作,forEach中直接调用未使用await,也未处理Promise拒绝。即使主函数执行,程序可能在Webhook发送完成前就终止,但因为主函数没运行,这个问题也不会显现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:25:30