我有一个observable,http处理其他observable中间.
如果http get响应代码不是200,我想记下这个错误,但继续下一个observable.
如果http get响应代码不是200,我想记下这个错误,但继续下一个observable.
到目前为止我有这个:
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'));
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') // ); }
上述情况产生400响应代码.我想记录该返回但继续其他可观察对象.
怎么做?
解决方法
您可以使用catch来处理
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); });
}