Home > Net >  How do I create a simulated API call in rxjs that throws an error after 1 second?
How do I create a simulated API call in rxjs that throws an error after 1 second?

Time:02-18

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

CodePudding user response:

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') }), or

  • switchMap(() => 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.

CodePudding user response:

This is a working example, inspired by @JSmart523

const apiCall = (callNumber: number, isError = false) =>
  of('Api Call Result '   callNumber).pipe(
    tap((_) => console.log('some log before')),
    delay(1000),
    switchMap((_) => {
      if (isError) {
        throw new Error(`ERROR`);
      } else {
        return of(_);
      }
    })
  );

apiCall(99, true).subscribe({
  next: (x) => console.log(x),
  error: (e: Error) => console.log(e.message),
});
  • Related