Heroku部署Discord机器人调用meme接口报FetchError解析异常
问题排查结论
这个报错和Heroku平台请求限制无关。
报错FetchError: invalid json response body at https://some-random-api.ml/meme reason: Unexpected token < in JSON at position 0的核心原因是,请求的目标接口返回了以<开头的HTML格式内容(通常是服务下线提示、域名跳转页、服务端错误页),而非代码预期的JSON格式,因此JSON解析流程直接失败。该问题在本地环境运行同样会触发,和部署平台没有关系。
根因是你引入的random-memes依赖对接的上游meme接口已经失效,当前访问该接口地址不会返回正常的meme数据。
代码问题与修复方案
你贴出的业务代码没有语法层面的错误,存在两个可优化/修复点:
- 核心问题:依赖绑定的上游API服务不可用,要么更换对接了可用meme接口的同类依赖包,要么手动修改
random-memes包内的请求地址为该API官方最新的可用域名。 - 缺失异常捕获:现有代码没有处理接口请求失败的场景,一旦接口报错会抛出未捕获的Promise异常,严重时会导致机器人进程意外退出。
修复后带异常处理的参考代码如下:
const memes = require("random-memes"); const { randomHexColor } = require('../admin/colorgen.js'); module.exports = { name: 'meme', description: 'Never mind what the description is!', async execute(message, args, Discord, Client, bot) { try { const meme = await memes.random(); const newEmbed = new Discord.MessageEmbed() .setColor(randomHexColor()) .setTitle(meme.caption) .setDescription(`category: ${meme.category}`) .setImage(meme.image); message.channel.send({ embeds: [newEmbed] }); } catch (error) { message.channel.send('meme生成服务暂时不可用,请稍后重试'); console.error('meme接口请求异常:', error); } } }
内容的提问来源于stack exchange,提问作者ION606
相关产品推荐
相关产品推荐

