I’m sending some values to an rxjs pipe followed by a subscription. In case of error
s, 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
Yes, when an
failIfError
occurs error thencatchError
returns thenull
and stops the process. So, please use theform
operator in theconcatMap
function.Please use the below code
The
from(failIfError(item))
it will return as Observable and you can handle the error withcatchError
.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.