我已经开发了一个与FTP服务器交互的node.js/express.js应用程序,问题是,如果服务器离线脱机,则应用程序崩溃,因为我找不到一个处理EDIMEDOUT例外的方法。顺便说一句,我用于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 */ }
附加到路由器函数上,但随后我得到了 TypeError: router.post(...).on is not a function
。
有人有任何建议吗?我很感激。
您发行的问题类似于此问题
这些步骤是处理错误并重试。
http.Client.on('error', function (err) {
/* handle errors here */
if (err.message.code === 'ETIMEDOUT') {
/* apply logic to retry */ }
})
使用node-retry保持重试逻辑简单。
我发现了如何处理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
});