简体   繁体   English

角度 try catch 与 catcherror

[英]angular try catch vs catcherror

For an angular project I am given an url that contains a list of all api paths (discover path).对于 angular 项目,我得到了一个包含所有 api 路径列表(发现路径)的 url。 In my application I want to call the discover path and save the results in a list.在我的应用程序中,我想调用发现路径并将结果保存在列表中。 My code:我的代码:

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.');
    }
  }

My question is when does it go to catchError and when to catch?我的问题是什么时候去 catchError 以及什么时候去捕获? If the call is succesfull but returns a error 500 does it go the the catcherror is is it going to catchError or is it a valid response (the call worked right)?如果调用成功但返回错误 500 是否会发生 catcherror 是它会发生 catchError 还是一个有效的响应(调用工作正常)? And how should the calling method handle the possible error.以及调用方法应该如何处理可能的错误。 Is it correct when I call with 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;
      })
    );
  }

Or should it be with a try catch.或者应该与尝试捕获一起使用。

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

In short when should the try/catch vs catcherror be used and how should I catch the error thrown in a catcherror/try catch from a calling method?简而言之,什么时候应该使用 try/catch 与 catcherror,我应该如何从调用方法捕获 catcherror/try catch 中抛出的错误?

In Synchronous programming we use traditional try catch block to catch any errors that are thrown.在同步编程中,我们使用传统的 try catch 块来捕获抛出的任何错误。

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

But when its asynchronous programming like an HTTP request we cannot rely on this try catch block,但是当它像 HTTP 请求这样的异步编程时,我们不能依赖这个 try catch 块,

So Rxjs provides this catchError a function that takes in an input Observable, and outputs an Output Observable.所以 Rxjs 为这个 catchError 提供了一个函数,它接收一个输入 Observable,并输出一个输出 Observable。

That function is expected to return an Observable which is going to be a replacement Observable for the stream that just errored out.该函数预计将返回一个 Observable,它将作为刚刚出错的流的替代 Observable。

as per your first question!根据你的第一个问题! It will always go to catchError because http.get an observable which makes it async它总是会去 catchError 因为 http.get 一个 observable 这使得它异步

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

Try catch is used for normal catching error in js code try catch 用于在js代码中正常捕获错误

Like this像这样

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

catchError is used for observable error catchingcatchError用于可观察的错误捕获

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