Try/Catch 不防止崩溃

Try/Catch does not prevent crash

我正在使用 telegraf bot framework 编写一个非常简单的电报机器人。 到目前为止,它使用 .hears.on 方法回复了一些简单的命令,到目前为止一切正常。

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

const Telegraf = require('telegraf')

const app = new Telegraf('<MY_TOKEN>')

// Connect/Express.js integration
const express = require('express')
const expressApp = express()

expressApp.set('port', (process.env.PORT || 5000));


app.command('start', (ctx) => {
  console.log('start', ctx.from)
  ctx.reply('Welcome!')
})

app.hears('Hi', (ctx) => ctx.reply('Hallo!'))
app.hears('Marco', (ctx) => ctx.reply('Polo'))
app.on('sticker', (ctx) => ctx.reply('❤'))

app.hears('Miez',(ctx) => {
    try{
          return ctx.replyWithDocument({
            url: 'http://thecatapi.com/api/images/get?format=src&type=gif',
            filename: 'cat.gif'
          })

       }catch(error){
            return ctx.reply("Miau");
       }
})

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

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
    at ClientRequest.<anonymous> (/app/node_modules/telegraf/node_modules/node-fetch/index.js:133:11)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at Socket.socketErrorListener (_http_client.js:310:9)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at connectErrorNT (net.js:1022:8)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)
  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',
  name: 'FetchError',
  errno: 'ENOTFOUND',
  type: 'system',
  code: 'ENOTFOUND' }

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

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

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

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

By default Telegraf will print all errors to stderr and rethrow error. To perform custom error-handling logic use following snippet:

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

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

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