Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable error handling by Angular's ExceptionHandler

I would like Angular's ExceptionHandler to handle any errors that occur from API calls. The problem is they never reach the ExceptionHandler's handleError method and I'm not sure what I need to do different.

// 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 }
 );
like image 673
user895400 Avatar asked Jun 07 '26 17:06

user895400


1 Answers

Looks like zone is not able to catch the error to pass it to Angular ErrorHandler. May be map will do the trick.

     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(); 
like image 175
Julia Passynkova Avatar answered Jun 09 '26 07:06

Julia Passynkova



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!