2017-01-03 38 views
1

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

现在我实现了另一个.hears方法,它正在等待字符串Miez。一旦它“听到”这个字符串,它应该是.replyWithDocument包含一个cat-api网址。根据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"); 
     } 
}) 

因此,大家可以看到我挤包在一个try/catch块.replyWithDocument。我这样做是因为给定的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,方法调用仍然失败。如果这可能是原因,那么如何处理呢?

+0

如果replyWithDocument是基于承诺,使用.catch()。如果它基于回调,则处理回调中的错误参数。 –

回答

4

您需要使用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