Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How to handle connect error 5 times and create an exception?

    try {
        await sqlConnection()
    }
    catch (e) {
        console.log(e);
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
130 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you're just trying to retry 5 times in case of any error and then fail with an error after 5 errors and sqlConnection() returns a promise that resolves when successful and rejects when there's an error, you can do something like this:

function delay(t) {
    return new Promise(resolve => {
        setTimeout(resolve, t)
    })
}

function connect(retries = 5, pauseTime = 100) {
    let cntr = 0;

    function run() {
        ++cntr;
        return sqlConnection().catch(err => {
            console.log(err);
            if (cntr < retries) {
                return delay(pauseTime).then(run);
            } else {
                // let promise reject
                throw err;
            }
        });
    }
    return run();
}

connect(5, 100).then(db => {
   // connected here
}).catch(err => {
   // failed to connect here
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...