如何处理连接错误5次并创建异常?
try {
await sqlConnection()
}
catch (e) {
console.log(e);
}
答案 0 :(得分:0)
如果您只是在发生任何错误时尝试重试5次,然后在5次错误后失败并显示错误,并且sqlConnection()
返回成功时解析的承诺并在出现错误时拒绝,则可以执行像这样的东西:
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
});
答案 1 :(得分:0)
只需使用循环:
for (let tries = 5; true; tries--) {
try {
await sqlConnection()
break; // a `return` works even better
} catch (e) {
console.log(e);
if (tries < 0)
throw e;
}
}