Catcherror In Angular

Catcherror In Angular

The RxJs operator Angular CatchError is used in Angular. It can be used to handle the errors that the Angular Observable throws. The CatchError, like all other RxJs operators, accepts an observable as input and returns an observable (or throws an error). We can use CatchError to throw a user-defined error or give a substitute observable. Let's have a look at all of them in this article.

Handling Errors in Observable

We have two options for dealing with mistakes.

  1. Using the subscribe method's error callback
  2. Errors in the observable stream should be Catch.

Using The Error Callback of Subscribe method

The subscribe method is used to subscribe to an Observable. As parameters, the subscribe method accepts three callback methods. The next value, error, or complete event is what they are. The error callback is used to catch and manage errors.

Consider the following code as an example. The map operator is used by the obs observable to multiply the values (srcArray) by two. If the result is NaN, we throw an error with the throw new Error function ("Result is NaN").

srcArray = from([1, 2, 'A', 4]);

obs = this.srcArray
  .pipe(
    map(val => {
      let result = val as number * 2;
      if (Number.isNaN(result)) {
        console.log('Errors Occurred in Stream')
        throw new Error("Result is NaN")
        }
        return result
      }),
  );

ngOnInit() {

  this.obs.subscribe(
    el => {
      console.log('Value Received ' + el)
    },
    err => {
      console.log("Error caught at Subscriber " + err)
    },
    () => console.log("Processing Complete.")
  )
}
 
 
**** Output *****
Value Received 2
Value Received 4
Errors Occurred in Stream
Error Caught at subscriber Error: Result is NaN

In the ngOnInit method, we subscribe to the obs observable and begin receiving values from it. The error callback is invoked when the observable stream throws an error. We determine what to do with the error in the error callback.

It's worth noting that if the observable fails, it won't emit any values or call the entire callback. The final value of 8 will never be received using our subscription mechanism.

Catch errors in the observable stream

The CatchError Operator is another alternative for catching errors. The CatchError Operators are used to catch errors in the observable stream as they occur. This gives us the option of retrying the failed observable or switching to a different observable.

Using CatchError Operator

We must import the CatchError operator from the rxjs/operators folder to use it, as seen below.

import { catchError } from 'rxjs/operators'

Syntax

The catchError operator can be piped. It can be used in a Pipe method just like the other operators like Map and so on.

Two arguments are passed to the catchError operator.

The first argument is err, which is the caught error object.

The source observable, which is the second argument, is caught. We may effectively restore it by retrying the observable.

Alternatively, catchError can throw an error if it does not return a new observable.

Returning a new observable

The catchError operator is demonstrated in the following examples.

srcArray = from([1, 2, 'A', 4]);
 
obs = this.srcArray
  .pipe(
    map(val => {
      let result = val as number * 2;
      if (Number.isNaN(result)) {
        console.log('Errors Occurred in Stream')
        throw new Error("Result is NaN")
      }
      return result
    }),
    catchError(error => {
      console.log('Caught in CatchError. Returning 0')
      return of(0);     //return from(['A','B','C'])
    })
  );
 
 
//Output
Value Received 2
Value Received 4
Errors Occurred in Stream
Caught in CatchError. Returning 0
Value Received 0
Observable Completed

The map emits the numbers 2 and 4 in the code above, which are passed to the catchError. Because there are no errors, catchError sends the message to the output. As a result, subscribers will receive values 2 and 4.

When the map operator throws an error, the catchError comes into action. The catchError method must deal with the issue and return a new observable (or throw an error). In the preceding example, we return a new observable, i.e. (0). You can also emit any observable, such as return from(['A','B','C']) or return from(['A','B','C']) and so on.

Throws a new Error

An error can also be thrown using catchError. To throw a JavaScript error, we use the throw new Error(error) method in the following example. As seen in the sample below, this error will be passed on to the subscriber.

obs = this.srcArray
  .pipe(
    map(val => {
      let result = val as number * 2;
      if (Number.isNaN(result)) {
        console.log('Errors Occurred in Stream')
        throw new Error("Result is NaN")
      }
      return result
    }),
    catchError(error => {
      console.log('Caught in CatchError. Throwing error')
      throw new Error(error)
    })
  );
 
 
//OUTPUT
Value Received 2
Value Received 4
Errors Occurred in Stream
Caught in CatchError. Throwing error
Error caught at Subscriber Error: Error: Result is NaN

ThrowError can also be used to return an observable. Remember that throwError produces an observable that emits an error immediately rather than throwing an error like throw new Error.

obs = this.srcArray
  .pipe(
    map(val => {
      let result = val as number * 2;
      if (Number.isNaN(result)) {
        console.log('Errors Occurred in Stream')
        throw new Error("Result is NaN")
      }
      return result
    }),
    catchError(error => {
      console.log('Caught in CatchError. Throwing error')
      return throwError(error);
    })
  );
 
//OUTPUT
Value Received 2
Value Received 4
Errors Occurred in Stream
Caught in CatchError. Throwing error
Error caught at Subscriber Error: Result is NaN

Retrying

You can also use the Retry operator to retry the observable.

obs = this.srcArray
.pipe(
  map(val => {
    let result = val as number * 2;
    if (Number.isNaN(result)) {
      console.log('Errors Occurred in Stream')
      throw new Error("Result is NaN")
    }
    return result
  }),
  retry(2),
  catchError((error,src) => {
    console.log('Caught in CatchError. Throwing error')
    throw new Error(error)
  })
);
 
 
//Output
Value Received 2
Value Received 4
Errors Occurred in Stream
Value Received 2
Value Received 4
Errors Occurred in Stream
Value Received 2
Value Received 4
Errors Occurred in Stream
Caught in CatchError. Throwing error
Error caught at Subscriber Error: Error: Result is NaN

The source observable is passed as the second argument to catchError. If we return it, the observable will be subscribed again, effectively retrying it.

Ensure that you keep track of the number of tries so that the observable can be turned off after a few failed attempts. Otherwise, if the observable always returns an error, you can end up in an infinite loop.

obs = this.srcArray
.pipe(
  map(val => {
    let result = val as number * 2;
    if (Number.isNaN(result)) {
      console.log('Errors Occurred in Stream')
      throw new Error("Result is NaN")
    }
    return result
  }),
  catchError((error,src) => {
    console.log('Caught in CatchError. Throwing error')
    this.count++;
    if (this.count < 2) {
      return src;
    } else {
      throw new Error(error)
    }
  })
);

Conclusion

In this article, we learned what is Catcherror in angular and how to use it.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post