簡體   English   中英

角度 try catch 與 catcherror

[英]angular try catch vs catcherror

對於 angular 項目,我得到了一個包含所有 api 路徑列表(發現路徑)的 url。 在我的應用程序中,我想調用發現路徑並將結果保存在列表中。 我的代碼:

discover(): Observable<ApiLink[]> {
    if (this.links) {
      return of(this.links);
    }
    try {
      console.log('calling :', URL);
      return this.http.get<{links: ApiLink[]}>(URL, {headers: this.headers}).pipe(
        map(response => {
          this.links = response.links;
          return this.links;
        }),
        catchError(some_error => {
          console.log('error ', some_error);
          throw new Error('failed to discover the api.');
        }),
      );
    } catch (e) {
      console.log('api discover failed ', e);
      throw new Error('failed to discover the api.');
    }
  }

我的問題是什么時候去 catchError 以及什么時候去捕獲? 如果調用成功但返回錯誤 500 是否會發生 catcherror 是它會發生 catchError 還是一個有效的響應(調用工作正常)? 以及調用方法應該如何處理可能的錯誤。 當我用 catcherror 調用時是否正確:

  // we give a string that relates to a path e.g. 'user' returns someurl.com/api/users
  url(rel: string, params?: object): Observable<string> {
    return this.discover().pipe(
      map(links => {
        const link = links.find(item => item.rel === rel);
        if (link) {
          return link.href;
        } else {
          throw new Error(`IXapi entry "${rel}" was not found.`);
        }
      }),
      catchError( errormessage => {
        console.log('error inside url ', rel, ' error:', errormessage);
        throw errormessage;
      })
    );
  }

或者應該與嘗試捕獲一起使用。

  url(rel: string, params?: object): Observable<string> {
    console.log('url: ', rel);
    try{
    return this.discover().pipe(
     // do stuff
    );
    }catch(e)
     {
       console.log('do some stuff because we have an error');           
       throw e;
     }
  }

簡而言之,什么時候應該使用 try/catch 與 catcherror,我應該如何從調用方法捕獲 catcherror/try catch 中拋出的錯誤?

在同步編程中,我們使用傳統的 try catch 塊來捕獲拋出的任何錯誤。

try {
   // synchronous operation
   const httpResponse =  getHttpResponseSync('/api/getUsers');
}
catch(error) {
    // handle error
}

但是當它像 HTTP 請求這樣的異步編程時,我們不能依賴這個 try catch 塊,

所以 Rxjs 為這個 catchError 提供了一個函數,它接收一個輸入 Observable,並輸出一個輸出 Observable。

該函數預計將返回一個 Observable,它將作為剛剛出錯的流的替代 Observable。

根據你的第一個問題! 它總是會去 catchError 因為 http.get 一個 observable 這使得它異步

參考https://www.intertech.com/Blog/angular-best-practice-rxjs-error-handling/

try catch 用於在js代碼中正常捕獲錯誤

像這樣

try {
  adddlert("Welcome guest!");
}
catch(err) {
  document.getElementById("demo").innerHTML = err.message;
}

catchError用於可觀察的錯誤捕獲

import { throwError, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
//emit error
const source = throwError('This is an error!');
//gracefully handle error, returning observable with error message
const example = source.pipe(catchError(val => of(`I caught: ${val}`)));
//output: 'I caught: This is an error'
const subscribe = example.subscribe(val => console.log(val));

暫無
暫無

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

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