【问题标题】:How to handle ETIMEDOUT in Express.js如何在 Express.js 中处理 ETIMEDOUT
【发布时间】:2018-06-01 08:15:18
【问题描述】:

我开发了一个与 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

有人有什么建议吗?我很感激。

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    我发现了如何在 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
    });
    

    【讨论】:

      【解决方案2】:

      你的问题类似于this question

      步骤是处理错误并重试。

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

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

      【讨论】:

      • 尝试给我“TypeError: express.on is not a function”,即使 Express 在我的代码中正确导入了“const express = require("express");”。
      • 抱歉,它是http.Client 的一部分,您可以find more information hereexpress 是一个错字
      猜你喜欢
      • 2023-03-28
      • 2013-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 2023-01-20
      • 1970-01-01
      相关资源
      最近更新 更多