Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular try catch vs catcherror

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

like image 599
Sven van den Boogaart Avatar asked Dec 09 '19 09:12

Sven van den Boogaart


2 Answers

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/

like image 184
Shashank Avatar answered Sep 29 '22 07:09

Shashank


Try catch is used for normal catching error in js code

Like this

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

catchError is used for observable error catching

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));
like image 45
Tony Ngo Avatar answered Sep 29 '22 08:09

Tony Ngo