i使用 backoff 方法的概念在发生内部服务器错误时重试该请求。我的意思不是 401
, 403
或类似。我的目标是如果服务器未响应和/或发送响应时间太长,例如,在 pending
状态时,请重试该请求。我确实对此定义了超时限制(在服务中(。
我的问题是 retryWhen
在所有情况/错误中都调用功能,包括 401
。
我相信我可能必须重组我的功能/代码才能使其起作用。我正在为此而苦苦挣扎,但不能使它正如预期的那样工作。
retryWhen
函数返回一个可观察的流,该流表示何时重试,因此它不能在我的代码中工作。
public userLogin(userName, userPass: string) {
this.theService.login(userName, userPass)
.retryWhen(attempts => Observable.range(1, 3)
.zip(attempts, i => i)
.mergeMap(i => {
console.log("delay retry by " + i + " second(s)");
// Show a message to user to wait
if ( i === 3 ) {
// Show Server doesn't respond... try later
}
return Observable.timer(i * 3000);
})
).subscribe(
res => {
// handle and show response result
},
err => {
console.log(err);
if ( err === 401 ) {
// handle 401 error
} else {
// handle other error
}
}
);
}
以下问题也是一种处理相同问题的一种问题,我试图使用有关mergeMap(error => {...})
的提示,但对我不起作用。
有什么想法,请如何重组我的代码以在内部服务器错误或某种情况下重试该请求?正如我提到的,没有 401
, 403
或类似。
您可以在retryWhen
运算符中重新列入黑名单的错误:
/**
* Performs a retry on an exponential backoff with an upper bounds.
* Will rethrow the error if it is in the blacklist or the retry
* attempts have exceeded the maximum.
* @param {number} initialDelay
* @param {number} maxRetry - maximum number of times to retry
* @param {number[]} errorWhiteList - whitelist of errors to retry on (non-transient)
*/
function expontentialRetry(
initialDelay,
maxRetry,
errorWhiteList
) {
return (errors) => errors.scan((retryAttempts, error) => {
if(!errorWhiteList.includes(error.status) || retryAttempts > maxRetry) {
throw error;
}
return retryAttempts + 1;
}, 0).switchMap((retryAttempts) => {
// calculate exponential backoff
let delay = Math.pow(2, retryAttempts - 1) * initialDelay;
console.log(`Retry attempt #${retryAttempts} in ${delay}ms`);
return Rx.Observable.timer(delay);
});
}
let count = 0;
const fakeApiCall = Rx.Observable.create((o) => {
if (count < 5) {
o.error({ status: 504 });
} else {
o.error({ status: 500 });
}
count++;
});
fakeApiCall.retryWhen(expontentialRetry(100, 10, [504]))
.subscribe(
(x) => { console.log('next', x); },
(error) => { console.log('error', error); },
() => { console.log('complete'); }
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.10/Rx.min.js"></script>