简体   繁体   中英

How to handle ETIMEDOUT in Express.js

I've developed a Node.js/Express.js application that interacts with a FTP server, the problem is that if the server is offline the application crashes because I can't find a way to handle the ETIMEDOUT exception. The module I'm using for FTP is jsftp, by the way.

The part of the code where it happens looks like this:

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);
    }
});

I tried appending a .on('error', function(e) { /* my code here */ } to the router.post function, but then I get TypeError: router.post(...).on is not a function .

Does anyone have any suggestion? I appreciate it.

You issue is similar to this question

The steps are to handle the error and to retry.

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

use node-retry to keep the retry logic simple.

I found out how to handle exceptions in a jsftp connection, it's very similar to what @neo proposed, but you gotta use your connection instance.

This is what has worked:

let conn = new jsftp(ftp);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM