Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

For an angular project I am given an url that contains a list of all api paths (discover path). 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? 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)? And how should the calling method handle the possible error. Is it correct when I call with 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);
    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?

Any error thrown anywhere inside in a chain that isn't caught manually is propagated as error notification that you can later catch with catchError – martin Dec 9, 2019 at 9:29

In Synchronous programming we use traditional try catch block to catch any errors that are thrown.

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,

So Rxjs provides this catchError a function that takes in an input Observable, and outputs an Output Observable.

That function is expected to return an Observable which is going to be a replacement Observable for the stream that just errored out.

as per your first question! It will always go to catchError because http.get an observable which makes it async

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

What is the proper way to handle the fail of the discover() method when calling discover should it be catchError again because it returns an observable? – Sven van den Boogaart Dec 9, 2019 at 9:41 thanks for the answer, what happens if the server responds with a 404 is it caught by catcherror? or is it given as response (as the get call went fine) – Sven van den Boogaart Dec 9, 2019 at 10:10
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));
                so in my question the  first catch that logs'api discover failed ' should never be reached?
– Sven van den Boogaart
                Dec 9, 2019 at 9:26
                @SvenvandenBoogaart if you mispell get, this is an synchronous error, so your try/catch gets involved. Asynchronous errors, instead, will go to catchError
– Christian Vincenzo Traina
                Dec 9, 2019 at 9:31
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.