运行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

