簡體   English   中英

Angular 和 RxJS - catchError() 不會捕獲請求錯誤

[英]Angular and RxJS - catchError() wont catch the request error

更新:我找到了問題。 答案如下

我的服務 class 中有以下代碼:

public getListById(id:string): Observable<any[]> {
        return this.http.get<any[]>(`${BASE_URL.local}/${id}`).pipe(
            map(obj => obj),
            catchError(error => this.handleError(error))
        )
    }

handleError(error: any): Observable<any> {
        console.log(error)
        this.snackBar.open(
            "Server Error",
            "X"
        )
        return EMPTY;
    }

以及我的組件中的以下代碼:

this.myService.getListById(id).subscribe(
    res => { doSomethingWith(res) },
    error => { 
        this.noRows = true
        console.log(error)
    },
    () => { this.loading = false }
)

當服務在 Rest 地址中調用 GET 時,它會給出 500 錯誤,我想處理它。

但是由於某種原因, pipe()中的catchError() function 沒有捕獲錯誤,並且僅在subscribe()中運行() => { this.loading = false }代碼。

這個糟糕的 RxJs 模塊(說真的,我不喜歡它處理后端請求的方式)我做錯了什么,我不能簡單地處理請求錯誤?

謝謝你。

回答

我發現了這個問題。 另一位之前的開發人員定義了一個錯誤攔截器,它沒有按應有的方式工作。

我刪除了ErrorInterceptor並定義了一個新的。 我還修復了app.module.ts中的“提供者”屬性定義,它沒有引用正確的 ErrorInterceptor class 。

這正是catchError已捕獲錯誤的標志。

handleError返回EMPTY ,這意味着關閉 stream 而不發出發射。 由於 stream 已關閉,您會看到this.loading = false

debugger放在console.log(error)之前並打開開發人員工具來檢查變量,也許this.snackBar.open有問題。

我知道這是不同的,但嘗試改變這樣的行為:

return this.http.get<any[]>(`${BASE_URL.local}/${id}`).pipe(
  catchError(err => {
    this.errorObject = err;
    return throwError(err);
  })
);

public errorObject = null;

默認設置錯誤為 null: this.errorObject = null;

暫無
暫無

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

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