Observable error handling with Angular ExceptionHandler

I would like Angular ExceptionHandler to handle any errors thrown from API calls. The problem is they never reach the ExceptionHandler handleError method and I'm not sure if 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 }
 );

      

+3


source to share


2 answers


It looks like the zone cannot catch the error so that it can be passed to the Angular ErrorHandler. Maybe the card 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(); 

      

+1


source


Put it like this:

.catch(this.handleError);

      



Example:

    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);
    }

      

0


source







All Articles