Angular Js

Error Handling in the Observable in Angular

Error Handling in the Observable in Angular

Catcherror in Angular Observable

Dealing with errors is one of the most challenging challenges in asynchronous programming. We cannot simply apply the try/catch/finally strategy that we employ when dealing with blocking code, as opposed to interactive style programming.

An RxJs Operator is Angular CatchError. It can be used to handle errors that the Angular Observable throws. The CatchError operator uses an observable as input and output much like the other RxJs operators do (or throws an error). We can throw a user-defined error or offer a substitute observable using CatchError.



ngOnInit() {

    const customObservable =
     Observable.create((observer) => {

        let count = 0;

        setInterval(() => {
        //emit a new value
        observer.next(count);
            if (count === 2) {
            observer.complete();
            }
            if (count > 3) {
            observer.error(
            new Error("Count is greater than 3"));
            }
            count++;
        }, 1000);
    });


    //subscribe to above observable
    customObservable.subscribe((data) => {
      console.log(data);
    });
}


Catch error throw above

//subscribe to above observable

this.firstObsSubscription =
  customObservable.subscribe(
      (data) => {
        console.log(data);
      },
      (error) => {
        console.log(error);
      },
      () => {
        console.log("completed !");
      }
  );





Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram