如何处理Express.js中的ETIMEDOUT

时间:2017-12-18 23:08:44

标签: javascript node.js express

我开发了一个与FTP服务器交互的Node.js / Express.js应用程序,问题是如果服务器处于脱机状态,应用程序崩溃,因为我找不到处理ETIMEDOUT异常的方法。顺便说一句,我用于FTP的模块是jsftp。

代码中发生的部分如下所示:

router.post("/", upload, function(req, res, next) {
    try {
        ftp.auth(ftp.user, ftp.pass, function(error) {
            if(error) {
                res.status("500");
                res.end("Error: Couldn't authenticate into the FTP server.");
                console.log(error);
            } else {    // Authenticated successfully into the FTP server
                /* some code here */
            }
        });
    } catch(error) {    // Probably timeout error
        res.status("500");
        res.end("Internal Server Error");
        console.log(error);
    }
});

我尝试将.on('error', function(e) { /* my code here */ }附加到router.post函数,但后来我得到TypeError: router.post(...).on is not a function

有没有人有任何建议?我很感激。

2 个答案:

答案 0 :(得分:1)

您的问题类似于this question

步骤是处理错误并重试。

http.Client.on('error', function (err) { 
    /* handle errors here */ 
    if (err.message.code === 'ETIMEDOUT') { 
        /* apply logic to retry */ }
})

使用node-retry来保持重试逻辑的简单。

答案 1 :(得分:0)

我发现了如何在jsftp连接中处理异常,它与@neo建议的非常类似,但你必须使用你的连接实例。

这是有效的:

let conn = new jsftp(ftp);

conn.on("error", function(error) {  // If an exception was thrown throughout the FTP connection
    // Handle the error in here
});