簡體   English   中英

如何在計時器(rxjs)中繼續捕獲錯誤

[英]How to continue catchError in timer (rxjs)

我有一個服務,負責使用計時器每 x 秒執行一次 httpClient.get。 我需要這個計時器在服務啟動時開始運行,因此計時器服務構造函數中定義。 根據我的理解,訂閱應該在計時器范圍內注冊,如下所示(如果不需要,我不想更改它,除非它不正確)。

只要后端服務器沒有錯誤\\異常\\錯誤 500 異常,所有系統都可以正常工作。 現在,我需要兩件事:

  1. 每當后端服務器出現問題時,我都想捕獲錯誤
  2. 我希望觀察者根據計時器時間繼續運行(到下一個滴答聲),即使有異常。 我的最終結果應該是在出現異常時到達組件中的 popUpAlert 請參閱我的代碼 - 這是 webapi 控制器:
public IActionResult getSomeErrorAsTest()
{
    try
    {
        throw new Exception("Serer error");
    }
    catch(Exception ex)
    {
        return StatusCode(StatusCodes.Status500InternalServerError, new List<string>());
        //throw ex;
    }
}

這是服務(假設每個 get 請求中的數據都發生了變化——如果確實發生了,則無需實施):

export class MyService
{
    MyDataSubject = new Subject<any[]>();
    MyDataChanged :Observable>any[]> = this.MyDataSubject.asObservable();
    
    subscribe :Subscription;
    constructor(private httpClient : HttpClient)
    {
        this.subscribe = timer(0, 30000).pipe(
        switchMap(()=>
            this.getData())).subscribe();
    }
    getData()
    {
        return this.httpClient.get<any[]>(<controller url>)
        .pipe(
            tap(res =>
            {
                this.MyDataSubject.next(res);
            }),
            catchError(error =>
                {
                    debugger;//I would expect to catch the debugger here, but nothing happens
                    return throwError(error);
                })
            )
    }
}   

消費者組件:

export class MyComponent (private mySrv : MyService)
{
    getMyData()
    {
        let sub =this.mySrv.MyDataChanged.subscribe(result => doSomething(),
                                                    error=> popUpAlert());
    }
}

CatchError運算符允許處理錯誤,但不會改變 observable 的性質 - 錯誤是給定 observable 的最終條件,因此發射將停止。 CatchError允許在發生時發出期望值,而不是引發觀察者的錯誤回調( metasong )。 在此處輸入圖片說明

您可能希望處理內部 Observable 中的錯誤(即內部switchMap ),因此在那里拋出的錯誤不會冒泡到主流,這樣在發生錯誤后主流會繼續,如下所示:

  this.subscribe = timer(0, 30000)
    .pipe(
      switchMap(() => this.getData().pipe(catchError(x => of("handle error here"))))
      // catchError(...) don't handle error here
    )
    .subscribe();

暫無
暫無

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

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