skip to Main Content

I’m sending some values to an rxjs pipe followed by a subscription. In case of errors, I want to ignore them and continue with the remaining inputs.

of('foo', 'bar', 'error', 'bazz', 'nar', 'error', 'car').subscribe(...)

So I did this:

async function failIfError(item: string) {
  if (item === 'error') throw new Error('HTTP 500'); // Some error we cant control
  return item;
}

of('foo', 'bar', 'error', 'bazz', 'nar', 'error', 'car')
  .pipe(
    concatMap((item) => failIfError(item)),
    catchError((error) => of(null))
  )
  .subscribe((val) => console.log('value:', val));

Stackblitz: https://stackblitz.com/edit/rxjs-pfdtrr?devToolsHeight=33&file=index.ts

This is the actual output:

value: foo
value: bar
value: null

How can I modify this code so that it ignores the error (with null) and continue with the execution? So that the output looks like:

value: foo
value: bar
value: null
value: bazz
value: nar
value: null
value: car

2

Answers


  1. Yes, when an failIfError occurs error then catchError returns the null and stops the process. So, please use the form operator in the concatMap function.

    Please use the below code

    of('foo', 'bar', 'error', 'bazz', 'nar', 'error', 'car').pipe(
            concatMap((item) => from(failIfError(item)).pipe(catchError((error) => of(null)))))
          .subscribe((val) => console.log('value:', val));
    

    The from(failIfError(item)) it will return as Observable and you can handle the error with catchError.

    Login or Signup to reply.
  2. The iif operator comes in handy here, it allows you to pipe on it to catch the error and let the outer observable to continue.

    of('foo', 'bar', 'error', 'bazz', 'nar', 'error', 'car')
      .pipe(
        concatMap((item) =>
          iif(
            () => item === 'error',
            throwError(() => new Error('HTTP 422')),
            of(item)
          ).pipe(
            catchError((err) => {
              return of(null);
            })
          )
        )
      )
      .subscribe((val) => console.log('value:', val));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search