角度尝试catch vs catcherror

时间:2019-12-09 09:16:41

标签: javascript angular typescript ecmascript-6 rxjs

对于有角度的项目,我会得到一个包含所有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 vs catcherror?我该如何捕获调用方法中在catcherror / try catch中引发的错误?

2 个答案:

答案 0 :(得分:4)

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

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

但是,当它像HTTP请求那样进行异步编程时,我们不能依靠此try catch块,

因此,Rxjs向此catchError提供一个函数,该函数接受输入Observable,并输出Output Observable。

该函数应该返回一个Observable,它将替换刚刚出错的流的Observable。

根据您的第一个问题! 它总是会进入catchError,因为http.get一个可观察到的东西使它异步

引用https://www.intertech.com/Blog/angular-best-practice-rxjs-error-handling/

答案 1 :(得分:2)

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));