簡體   English   中英

rxjs 使用 catchError 和重試的錯誤處理

[英]rxjs error handling with catchError and retry

我正在嘗試使用 catchError 運算符捕獲 rxjs 中的錯誤,並且僅當我收到errno=215時才想重試 3 次

return this.httpService.post(url, data).pipe(
  tap(() => {
    console.log(`some debugging info`);
  }),

  map((response) => responseAdaptor(response)),
  retryWhen((error) => {
    return error.pipe(
      scan((acc, error) => {
        // RETRY ONLY IF ERROR error.errno == 215

        if (acc > 2) throw error;

        return acc + 1;
      }, 0),
      delay(1000)
    );
  }),
  catchError((error) => {
    console.log(error);

    // Here I want the use `throwError`

    return of({ error: error.response });
  })
);

這是我嘗試過的但不幸的是不知道如何結合掃描計數器和 errno。

您可以通過將catchError運算符移動到retryWhen之前,並使用take(3)運算符將重試嘗試限制為 3 次而不是使用scan一次來實現。

您可以嘗試以下操作:

this.httpService.post(url, data).pipe(
      tap(() => {
        console.log(`some debugging info`);
      }),
      map((response) => responseAdaptor(response)),
      catchError((error) => {
        // If the error is 215 then throw the error to trigger the retryWhen,
        // Otherwise return the error response.
        if (error.errno === 215) {
          return throwError(() => error);
        }
        return of({ error: error.response });
      }),
      retryWhen((errors) => errors.pipe(delay(1000), take(3)))
    );

這將在 3 次重試嘗試后完成主Observable 如果你想包裝錯誤並在 3 次嘗試后保持主Observable工作,則retryWhen回調返回的 observable 應該返回以下內容:

// This should be added directly after `take(3)` operator on the `errors` pipe.
concatMap((error) => of({ error: error.response })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM