RxJS - Error Handling Operator catchError



This operator takes care of catching errors on the source Observable by returning a new Observable or an error.

Syntax

catchError(selector_func: (err_func: any, caught: Observable) => O):Observable

Parameters

selector_funct − The selector func takes in 2 arguments, error function and caught which is an Observable.

Return value

It returns an observable based on the value emitted by the selector_func.

Example

import { of } from 'rxjs';
import { map, filter, catchError } from 'rxjs/operators';

let all_nums = of(1, 6, 5, 10, 9, 20, 40);
let final_val = all_nums.pipe(
   map(el => {
      if (el === 10) {
         throw new Error("Testing catchError.");
      }
      return el;
   }),
   catchError(err => {
      console.error(err.message);
      return of("From catchError");
   })
);
final_val.subscribe(
   x => console.log(x),
   err => console.error(err),
   () => console.log("Task Complete")
);

Output

catchError Operator
Advertisements