0

I'm using observables for Http calls, which have been working fine, but then I changed up my controllers and noticed that my code apparently isn't handling errors.

Here is a look at the code from my service (SellingMenuService):

public getVarieties(): Observable<any> {
    return this.http.get(this.varietyListUrl).map(response => {
        return response.json();
    }, (error: any) => {
        console.log(error);
        console.log('error finding variety list');
        // TODO: implement error handling here.
    });
}

And here is the relevant code from my component:

constructor(public sellingMenuService: SellingMenuService) { }

getVarietyList(): void {        
    this.sellingMenuService.getVarieties().subscribe(res => {            
        console.log(res);
        this.varieties = res;
    });         
}

And here are some errors in my console: enter image description here

If I'm getting a 500 error, shouldn't those console logs from my service above get hit? Why don't they?

Bryan
  • 2,951
  • 11
  • 59
  • 101
  • [Here is the official recommended way](https://angular.io/docs/ts/latest/guide/server-communication.html#!#error-handling) to handle exceptions on HTTP requests from _Angular.io_. There is a link to a [live example](https://embed.plnkr.co/?show=preview) on Plunker at the bottom of the page (go to `/app/toh/hero.service.ts` to see the code of the HTTP client service). – Alex Klaus May 29 '17 at 10:43

2 Answers2

1

You appear to have your error-handling logic inside map().

import 'rxjs/add/operator/catch';

return this.http.request(request)
  .map(res => res.json())
  .subscribe(
    data => console.log(data),
    err => console.log(err),
    () => console.log('yay')
  );

See: How to catch exception correctly from http.request()?

Community
  • 1
  • 1
Dan Wilson
  • 3,937
  • 2
  • 17
  • 27
1

You are trying to catch error in the map method, while you should do it inside subscribe.

public getVarieties(): Observable<any> {
    return this.http.get(this.varietyListUrl).map(response => {
        return response.json();
    }).subscribe((res: any) => {
        console.log(res);
    }, (error: any) => {
        console.log(error);
        console.log('error finding variety list');
        // TODO: implement error handling here.
    });
}

You can also add third parameter to observable. It will be resolved when observable is finalized:

public getVarieties(): Observable<any> {
    return this.http.get(this.varietyListUrl).map(response => {
        return response.json();
    }).subscribe((res: any) => {
        console.log(res);
    }, (error: any) => {
        console.log(error);
        console.log('error finding variety list');
        // TODO: implement error handling here.
    }, () => {
        console.log("finalized")
    });
}

You can read more here: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html

Maciej Treder
  • 11,866
  • 5
  • 51
  • 74