3

Error callback in subscribe is not mapped to JSON trough map function! Why?

this.http.get("/something")
            .map((response: any) => response.json())
            .subscribe((response: any) => {
                  // response is body of request
            }, (error: any) => {
                // error must be mapped again
                let error = JSON.parse(error._body);
            });
Vlado Tesanovic
  • 6,369
  • 2
  • 20
  • 31

2 Answers2

1

In fact, the callback specified with the map operator isn't called in the case of errors. You need to leverage the catch one to do that:

this.http.get("/something")
        .map((response: any) => response.json())
        .catch((response: any) => Observable.throw(response.json()))
        .subscribe((response: any) => {
              // response is body of request
        }, (error: any) => {
            // error must be mapped again
            let error = JSON.parse(error._body);
        });
MKroeders
  • 7,562
  • 4
  • 24
  • 39
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Technically, `map()` is called, but the function that it was passed as an argument does not get called because the Observable has no events, only an error. The error propagates. – Mark Rajcok Feb 19 '16 at 03:57
  • Yes, agreed with you @Mark! It's not the `map` method but the callback specified at its level. I updated my answer ;-) Thanks for pointing this out... – Thierry Templier Feb 19 '16 at 07:53
1

Because the Observable returned from get() has an error, the function that map() was passed is not called (because no events are emitted). I.e., arrow function (response: any) => response.json() is not called. Rather, the error propagates until something catches it. If nothing catches the error, you'll see the exception in your browser console.

You can catch the error with .catch() and/or by supplying an error handler in subscribe().

I tried to create a robust http error handler here: https://stackoverflow.com/a/35329086/215945
It catches errors generated from .get() or .json().

Community
  • 1
  • 1
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492