RxJs Observable - Handle 404 by emitting default value RxJs Observable - Handle 404 by emitting default value typescript typescript

RxJs Observable - Handle 404 by emitting default value


I think I may have figured this out. A hint was lurking in the browser console...

TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

Reading the RxJs documentation on error handling showed them doing what I'm trying to do, so I was a bit confused by this. But then I noticed that in the documentation they call a mystery function getCachedVersion() which I assumed returned an actual cached thing. However if they instead returned an Observable.of() some actual cached thing, then that might explain it.

When I changed my catch code to:

        .catch(function (e) {            if(e.status === 404) {                // no photo for this user!                console.log(`No photo for user ${id}!  Returning default...`);                return Observable.of(undefined);            }        })

...it all started working.


To translate Johns answer into an up-to-date rxjs implementation, this now looks like:

import { Observable, throwError, of } from 'rxjs';import { catchError } from 'rxjs/operators'; const observale: Observable<unknown>; observale.pipe(   catchError(err => {       if(err.error.statusCode === 404) {          return of(undefined);       } else {          //important to use the rxjs error here not the standard one          return throwError(err);       }   })).subscribe(val => {      console.log('success but may be undefined');   }, err => {      console.log('error');});