Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 error handling - send to subscribed component

I am using Angular 2 HTTP, and have a component subscribing to the response. However, when there is an error, the catch method does not return the error to the subscribed component. It just throws it in the console.

 saveFinalize(fcData: LastForecastInterface) {
    let responseData = JSON.stringify(fcData);
    let body = responseData;

    const headers = new Headers();
    headers.append('Content-Type', 'application/json;charset=UTF-8');

    return this.http.post('/saveFinalize', body, { headers: headers })
      .map((data: Response) => data.json())
      .catch(this.handleError);
}

public handleError(error: Response | any) {
    console.log('err: ', error)
    let errMsg: string;
    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    // return Observable.throw(errMsg);
    return errMsg;
}

And my subscribed component does not get back a response

saveFinalize() {
  this.loadingData = true;
  return this.httpService.saveFinalize(this.getFc.fcData)
    .subscribe(response => {
        this.loadingData = false;
        console.log(response);
        let saveResponse = response.success ? 'Successfully Saved Finalized!' : 'Error Saving Finalized! - ' + response.message;
        let respType = response.success ? 'success' : 'danger';
        this.alertSvc.showAlert(saveResponse, respType);
    });
}
like image 636
ahrobins Avatar asked Mar 15 '26 22:03

ahrobins


1 Answers

See this code here: (It is from https://angular.io/docs/ts/latest/guide/server-communication.html)

getHeroes() {
  this.heroService.getHeroes()
                  .subscribe(
                    heroes => this.heroes = heroes,
                    error =>  this.errorMessage = <any>error);
}

Notice there are 2 arguments for .subscribe() method. One is the response which you use, and the next one is the error. In order to pass the error to the subscribed component you must use the later argument, which will make your code looks like this:

  return this.httpService.saveFinalize(this.getFc.fcData).subscribe(response => {
    this.loadingData = false;
    console.log(response);
    let saveResponse = response.success ? 'Successfully Saved Finalized!' : 'Error Saving Finalized! - ' + response.message;
    let respType = response.success ? 'success' : 'danger';
    this.alertSvc.showAlert(saveResponse, respType);
  }, error => {
    // the errorMessage will be passed here in this "error" variable
  });

When the subscribed method returns a successful response, you will only get your response. But when the subscribed method throws an error you won't get your response, you will only get the error (which is the second argument of the subscribe() method).

You also need to throw the error from the handleError() method. So instead of only return the string value (return errMsg;), you should use return Observable.throw(errMsg);.

like image 98
samAlvin Avatar answered Mar 17 '26 11:03

samAlvin