Angular的ExceptionHandler可观察到的错误处理

时间:2017-04-27 14:50:15

标签: angular rxjs observable angular-http

我希望Angular的ExceptionHandler能够处理API调用中发生的任何错误。问题是它们从未到达ExceptionHandler的handleError方法,我不确定我需要做些什么。

// data.service.ts

addItem(name: string): Observable<any> {

  return this.http.post(name)
           .map(this.extractData)
           .catch((error) => this.handleError(error))
           .share(); 
}

private handleError(error: any): any {
  const msg = `${error.status} - ${error.statusText}`

  // this did not work
  //throw new Error(msg); 

  // also doesn't work
  return Observable.throw(new Error(msg));
}

// item.component.ts

 const observable = this.dataService.addItem('test');
 observable.subscribe(
   (success) => console.log('success'),
   (error) => { throw new Error('test'); // doesn't work }
 );

2 个答案:

答案 0 :(得分:1)

看起来区域无法捕获错误以将其传递给Angular ErrorHandler。可能是地图会做的伎俩。

     return this.http.post(name)
       .map(this.extractData)
       .catch((error) => this.handleError(error))
       .map(result=> {
         if(result === 'good one') { return 'good one'; }
         else { new Error(result);}
       })
       .share(); 

答案 1 :(得分:0)

就像这样:

.catch(this.handleError);

示例:

    public fetch(url, env = null): Observable<any> {
        return this.http
            .get(this.buildURL(url, env))
            .map(this.extractData)
            .catch(this.handleError);
    }

    private handleError(error: any) {
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }