Skip to content Skip to sidebar Skip to footer

How To Handle Connect Error 5 Times And Create An Exception?

How to handle connect error 5 times and create an exception? try { await sqlConnection() } catch (e) { console.log(e); }

Solution 1:

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:

functiondelay(t) {
    returnnewPromise(resolve => {
        setTimeout(resolve, t)
    })
}

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

    functionrun() {
        ++cntr;
        returnsqlConnection().catch(err => {
            console.log(err);
            if (cntr < retries) {
                returndelay(pauseTime).then(run);
            } else {
                // let promise rejectthrow err;
            }
        });
    }
    returnrun();
}

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

Solution 2:

Just use a loop:

for (let tries = 5; true; tries--) {
    try {
        awaitsqlConnection()
        break; // a `return` works even better
    } catch (e) {
        console.log(e);
        if (tries < 0)
            throw e;
    }
}

Post a Comment for "How To Handle Connect Error 5 Times And Create An Exception?"