Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle observable errors but continue with follow on observables?

I have an observable, does an http get in the middle of processing other observables. In the case of the http get response code of anything but 200, I want to take note of this error but proceed to the next observable.

So far I have this:

this.getConfigurationSettings()
    .do(config => {
        console.log('configuration settings.: ', config);
        this.configSettings = config;
        this.subscriptionService.setWSAddressProvider('badUrl');
    })
    .switchMap(config => this.askForWSData())
    .do(config =>
        console.log('askForWSData' + config))
    .switchMap(r => this.processWSData())
    .subscribe(
        config => {
            console.log('start of data processing: ' + config);
        },
        err => {
            // Log errors if any
            console.log(err);
        },
        () => console.log('app exiting'));

and the observable that can return an http error code is the following:

setWSAddressProvider() : Observable<string[]> {
    return this.http.get('badUrl')
        .map((res:Response) => {
            this.address = res.text();
            return [res.text()];
        });
        // .catch((error:any) =>
        // Observable.throw('Server error')
        // );
}

the above case generate a 400 response code. I want to log that return but go on to other observables. How to do that?

like image 795
reza Avatar asked Apr 17 '17 16:04

reza


1 Answers

You can use catch to handle http errors

setWSAddressProvider() : Observable<string[]> {
    return this.http.get('badUrl')
        .map((res:Response) => {
            this.address = res.text();
            return [res.text()];
        });
       .catch((error: Response | any) => {
           if (error instanceof Response) {
                if (error.status === 400) {
                    console.log("Server responded with 400");
                    // Create a new observable with the data for the rest of the chain
                    return Observable.of([]);
                }
           }
           // Re-throw unhandled error
           return Observable.throw(err);
    });

}

like image 81
Ofer Herman Avatar answered Sep 28 '22 17:09

Ofer Herman