ThrowError In Angular

ThrowError In Angular

In this article, we will learn how to use ThrowError In Angular. The Angular ThrowError operator returns an observable that immediately errors out after subscription. It doesn't provide any outcomes.

ThrowError

ThrowError is a function that creates a new observable. As a result, we must accept it. The following example builds and subscribes to a ThrowError observable.

import { Component, VERSION } from "@angular/core";
import { Observable, of, from, throwError } from "rxjs";
import { map, catchError } from "rxjs/operators";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular " + VERSION.major;
 
  obs = throwError("Error From ThrowError observable");
 
  ngOnInit() {
    this.obs.subscribe(
      el => {
        console.log("Value Received :" + el);
      },
      err => {
        console.log("Error caught at Subscriber :" + err);
      },
      () => console.log("Processing Complete")
    );
  }
}
 
 
 
****Console Window
 
Error caught at Subscriber: Error From ThrowError observable

First, we use throwError to construct an observable. The error object is the first input to throwError. When the error notification is raised, this error object is provided to the consumers.

obs = throwError("Error From ThrowError observable")

In the ngOnInit function, we subscribe to it.

this.obs.subscribe(

The observable raises the error notification and completes instantly. The error callback is called, and the error message appears in the console window.

err => {
  console.log("Error caught at Subscriber :" + err);
},

Throw Error Vs ThrowError

It's very simple to mix up the terms Throw Error and ThrowError.

Throw Error is a function that throws an error. It's a JavaScript construct that's not included in RxJs. To capture the mistakes thrown by the Throw Error, we must use the try/catch block. The try/catch block in RxJS is used to catch any errors thrown by the observables. When they find one, they send out an error notification (which raises the error callback), and the observable comes to a halt.

ThrowError does not throw errors in the same way that throw Error does. It then stops and returns a new observable that emits an error notification (raises the error callback).

Throw Error Example

import { Component, VERSION } from "@angular/core";
import { Observable, of, from, throwError } from "rxjs";
import { map, catchError } from "rxjs/operators";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
 
 
  srcArray = from([1, 2, "A", 4]);
 
  obs = this.srcArray.pipe(
    map(val => {
      let result = (val as number) * 2;
      if (Number.isNaN(result)) {
        console.log("Error in the observable");
        throw Error("Not a Number");
      }
      return result;
    })
  );
 
  ngOnInit() {
    this.obs.subscribe(
      el => {
        console.log("Value Received :" + el);
      },
      err => {
        console.log("Error caught at Subscriber :" + err);
      },
      () => console.log("Processing Complete.")
    );
  }
}
 
 
***Console ****
 
Value Received :2
Value Received :4
Error in the observable
Error caught at Subscriber :Error: Not a Number

Values 2 and 4 are emitted by the observable.

When a map operator receives the value A, it throws an error using the throw Error method. This error is caught by the observable, which raises an error message and then terminates.

The last value 8, on the other hand, is never transmitted.

ThrowError

Let's change throw Error to return throwError now.

import { Component, VERSION } from "@angular/core";
import { Observable, of, from, throwError } from "rxjs";
import { map, catchError } from "rxjs/operators";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular " + VERSION.major;
 
  srcArray = from([1, 2, "A", 4]);
 
  obs = this.srcArray.pipe(
    map(val => {
      let result = (val as number) * 2;
      if (Number.isNaN(result)) {
        console.log("Error in the observable");
        return throwError("Not a Number");
      }
      return result;
    })
  );
 
  ngOnInit() {
    this.obs.subscribe(
      (el: any) => {
        console.log("Value Received :" + el);
      },
      err => {
        console.log("Error caught at Subscriber :" + err);
      },
      () => console.log("Processing Complete.")
    );
  }
}
 
 
****Console ********
Value Received :2
Value Received :4
Error in the observable
Value Received :[object Object]
Value Received :8
Processing Complete

Values 2 and 4 are emitted by the observable.

The map operator throws an error when it receives the value A. It's important to remember that throwError returns an observable. Only if you subscribe to the error notification will it be raised.

The observable is not subscribed to by the map operator. It simply sends it back to the subscriber.

As a result, the throwError observable is passed to the subscriber as a value. As a result, [object Object] appears in the console.

The observable proceeds and emits the next value 8, then complete, because no error has been raised.

Using ThrowError

To receive error notifications, the throwError must be subscribed. It may be combined with other Observables like mergeMap, switchMap, catchError, and so on.

Using with catchError

The following example demonstrates how to use ThrowError in conjunction with CatchError.

import { Component, OnInit } from "@angular/core";
import { throwError, from } from "rxjs";
import { map, catchError } from "rxjs/operators";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  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. Throwing error");
      return throwError(error);
    })
  );
 
  ngOnInit() {
    this.obs.subscribe(
      el => {
        console.log("Value Received " + el);
      },
      err => {
        console.log("Error caught at Subscriber " + err);
      },
      () => console.log("Processing Complete.")
    );
  }
}
 
 
******* CONSOLE ******* 
Value Received 2
Value Received 4
Errors Occurred in Stream
Caught in CatchError. Throwing error
Error caught at Subscriber Error: Result is NaN

The throwing error in the map operator is used in the code to throw the error.

This error will be caught by CatchError. To manage the problems thrown by the Angular Observable, we use the CatchError. We must return an observable once we've handled the error. Either a replacement observable or an error can be returned. The observable produced by CatchError is subscribed right away.

As a result, we may use throwError, which is immediately subscribed and produces an error notification.

catchError(error => {
  console.log("Caught in CatchError. Throwing error");
  return throwError(error);
})

Using it with MergeMap

The Angular MergeMap converts each value from the source observable into an inner observable, subscribes to it, and then begins emitting its values.

When we obtain the value 3, we use throwError to return an observable in the following example. The MergeMap registers for this new observable raise an error notification and then exit.

import { Component, OnInit } from "@angular/core";
import { throwError, of } from "rxjs";
import { map, mergeMap, catchError } from "rxjs/operators";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  srcObservable = of(1, 2, 3, 4);
  innerObservable = of("A", "B");
 
  obs = this.srcObservable.pipe(
    mergeMap(val => {
      console.log("Source value " + val);
      console.log("starting new observable");
 
      if (val == 3) return throwError("Error in observable");
 
 
      return this.innerObservable;
    })
  );
 
  ngOnInit() {
    this.obs.subscribe(
      el => {
        console.log("Value Received " + el);
      },
      err => {
        console.log("Error caught at Subscriber " + err);
      },
      () => console.log("Processing Complete.")
    );
  }
}
 
 
***Console ****
Source value 1
starting new observable
Value Received A
Value Received B
Source value 2
starting new observable
Value Received A
Value Received B
Source value 3
starting new observable
Error caught at Subscriber Error in observable

Conclusion

In this article, we learned what is ThrowError 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