Demo: throwError
The throwError creates an observable that throws the given error upon subscription.
What is happenng in the demo ?
- The value maps to throwError observable for v==3
- As the mergeMap tries to get the output from throwError observable,
it throws the specified error.
- We are handling the thrown error using catchError.
//Add an error into the output if input from timer is 3
let input = timer(500,1000).pipe(mergeMap(v =>
(v==3)? throwError(()=>new Error("E")):of(v)
));
//in case of error convert it into an observable as specifed
let process = catchError(err => of('e'));
let output = input.pipe(process).subscribe(v=>console.log(v))
More on :
throwError
1. Equivalent for the demo code above
Instead of returning throwError
observable which throws the error when mergeMap tries
to get it's output, we can directly throw the error when value is 3 as shown below.
import {timer, mergeMap, catchError} from 'rxjs';
let input = timer(500,1000).pipe(mergeMap(v =>{
if(v==3){
throw new Error("E");
}else{
return of(v);
}
));
//in case of error convert it into an observable as specifed
let process = catchError(err => of('e'));
let output = input.pipe(process).subscribe(v=> console.log(v) )
2. Custom code for : throwError(()=>new Error("E"))
throwError
is a simple observable that emits no data but, throws the
specifed error when we subscribe.
import {Observable} from 'rxjs';
//Equivalent custom created throwError observable
let throwErrorObservable = new Observable((subscriber) =>{
throw new Error("E");
})
//Throws an exception upon subscription
throwErrorObservable
.subscribe(
( v ) => console.log(v),
(err) => console.log("Error occurred :"+err.message),
);
//Output: No data. We are catching only an error on subscription
Error occurred :E
Note : We can catch an error by handling it inside subscribe
method as shown
here or by using a catchError
operator as shown in the demo.