Try/Catch 不能防止崩溃

チーズ*_*ズパン 1 javascript heroku telegram telegram-bot telegraf

我正在使用telegraf bot 框架编写一个非常简单的 telegram-bot 。\n到目前为止,它使用.hears和回复了一些简单的命令.on,到目前为止一切正常。

\n\n

现在我实现了另一种.hears等待字符串的方法Miez。一旦它“听到”这个字符串,它就应该.replyWithDocument包含一个cat-api url。根据 cat-api 的 URL 在每次调用时都会提供一个随机的 cat-gif。到目前为止我的代码:

\n\n
const Telegraf = require(\'telegraf\')\n\nconst app = new Telegraf(\'<MY_TOKEN>\')\n\n// Connect/Express.js integration\nconst express = require(\'express\')\nconst expressApp = express()\n\nexpressApp.set(\'port\', (process.env.PORT || 5000));\n\n\napp.command(\'start\', (ctx) => {\n  console.log(\'start\', ctx.from)\n  ctx.reply(\'Welcome!\')\n})\n\napp.hears(\'Hi\', (ctx) => ctx.reply(\'Hallo!\'))\napp.hears(\'Marco\', (ctx) => ctx.reply(\'Polo\'))\napp.on(\'sticker\', (ctx) => ctx.reply(\'\xe2\x9d\xa4\'))\n\napp.hears(\'Miez\',(ctx) => {\n    try{\n          return ctx.replyWithDocument({\n            url: \'http://thecatapi.com/api/images/get?format=src&type=gif\',\n            filename: \'cat.gif\'\n          })\n\n       }catch(error){\n            return ctx.reply("Miau");\n       }\n})\n
Run Code Online (Sandbox Code Playgroud)\n\n

正如您所看到的,我将其包装.replyWithDocument在 try/catch 块中。我这样做是因为给定的url并不总是提供 gif。有时您只是收到一条Server not found消息。我在 Heroku 上托管机器人,以下是相应错误的日志:

\n\n
Failed to process updates. { FetchError: request to http://30.media.tumblr.com/tumblr_lu65p0QXgW1r4xjo2o1_r1_500.gif failed, reason: getaddrinfo ENOTFOUND 30.media.tumblr.com 30.media.tumblr.com:80\n    at ClientRequest.<anonymous> (/app/node_modules/telegraf/node_modules/node-fetch/index.js:133:11)\n    at emitOne (events.js:96:13)\n    at ClientRequest.emit (events.js:188:7)\n    at Socket.socketErrorListener (_http_client.js:310:9)\n    at emitOne (events.js:96:13)\n    at Socket.emit (events.js:188:7)\n    at connectErrorNT (net.js:1022:8)\n    at _combinedTickCallback (internal/process/next_tick.js:74:11)\n    at process._tickCallback (internal/process/next_tick.js:98:9)\n  message: \'request to http://30.media.tumblr.com/tumblr_lu65p0QXgW1r4xjo2o1_r1_500.gif failed, reason: getaddrinfo ENOTFOUND 30.media.tumblr.com 30.media.tumblr.com:80\',\n  name: \'FetchError\',\n  errno: \'ENOTFOUND\',\n  type: \'system\',\n  code: \'ENOTFOUND\' }\n
Run Code Online (Sandbox Code Playgroud)\n\n

抛出此错误后,机器人会停止在 Heroku 上工作一段时间,然后在 15 分钟左右再次恢复,我猜它会在一段时间不活动后重新启动。

\n\n

好吧,归根结底,我不介意 url 调用有时会失败。我不明白的是为什么我的 try/catch 块没有捕获这种行为。如果我对日志的解释是正确的。

\n\n

编辑:我想到了一个可能的原因,也许.replyWithDocument是异步调用。所以 HTTP 请求成功了,尝试也成功了。但是一旦响应,Server not found方法调用仍然失败。如果这可能是原因,那么该如何处理呢?

\n

Leo*_*cio 5

您需要使用 Telegraf 自定义错误处理方法!。

默认情况下,Telegraf 会将所有错误打印到 stderr 并重新抛出错误。要执行自定义错误处理逻辑,请使用以下代码片段:

const app = new Telegraf(process.env.BOT_TOKEN)
app.catch((err) => {
  console.log('Ooops', err)
})
Run Code Online (Sandbox Code Playgroud)

尝试使用上面的代码来捕获您的“ENOTFOUND”错误。

资料来源: http: //telegraf.js.org/introduction.html#error-handling