3

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

2 Answers 2

1

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(); 
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Hmm why should that matter? I did catch((error) => this.handleError(error)) because eventually I would to be able to pass my own custom messasge to show instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.