'How do I create a simulated API call in rxjs that throws an error after 1 second?
Play with the code here => https://stackblitz.com/edit/playground-rxjs-f8xjsh
Hi, I'm trying to simulate a failed API Call that will emit the error value at the subscribe() { Error: } part.
import { from, of, pipe, forkJoin, interval, AsyncSubject, BehaviorSubject,defer, Subject, timer, observable, throwError } from 'rxjs';
import { concatMap, map, mergeMap, zipWith, delay, tap, concatAll, concat, concatWith, switchMap, catchError } from 'rxjs/operators';
const apiCall = (callNumber, isError=false) => of('Api Call Result ' + callNumber).pipe(
tap(_=>console.log('Calling Api ' + callNumber)),
delay(1000),
tap(_=> throwError(() => new Error('ERROR')))
);
apiCall(99,true).subscribe({
next: x=>console.log(x),
error: e=>console.log(e)
});
Currently the error is not caught i.e. logged. Can someone help?
Stackblitz => https://stackblitz.com/edit/playground-rxjs-f8xjsh
Solution 1:[1]
tap executes the function and then emits whatever it received, unchanged.
throwError is a function that returns an observable.
So, someObservable.pipe(x) will return an observable that emits an error if x is
map(() => { throw new Error('msg') }), orswitchMap(() => throwError('msg'))
... or you can simply create a new observable with throwError('msg')) and there's no need to pipe anything...
but tap(() => anything) won't change what the observable emits.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JSmart523 |
