角度 try catch 与 catcherror

Sve*_*art 6 javascript rxjs typescript ecmascript-6 angular

对于 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.');
    }
  }
Run Code Online (Sandbox Code Playgroud)

我的问题是什么时候去 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;
      })
    );
  }
Run Code Online (Sandbox Code Playgroud)

或者应该与尝试捕获一起使用。

  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;
     }
  }
Run Code Online (Sandbox Code Playgroud)

简而言之,什么时候应该使用 try/catch 与 catcherror,我应该如何从调用方法捕获 catcherror/try catch 中抛出的错误?

小智 5

在同步编程中,我们使用传统的 try catch 块来捕获抛出的任何错误。

try {
   // synchronous operation
   const httpResponse =  getHttpResponseSync('/api/getUsers');
}
catch(error) {
    // handle error
}
Run Code Online (Sandbox Code Playgroud)

但是当它像 HTTP 请求这样的异步编程时,我们不能依赖这个 try catch 块,

所以 Rxjs 为这个 catchError 提供了一个函数,它接收一个输入 Observable,并输出一个输出 Observable。

该函数预计将返回一个 Observable,它将作为刚刚出错的流的替代 Observable。

根据你的第一个问题!它总是会去 catchError 因为 http.get 一个 observable 这使得它异步

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