Vlado Tesanovic
Vlado Tesanovic

Reputation: 6424

Error handler in Observable is not mapped to JSON

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

Upvotes: 3

Views: 1315

Answers (2)

Thierry Templier
Thierry Templier

Reputation: 202138

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

Upvotes: 1

Mark Rajcok
Mark Rajcok

Reputation: 364677

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().

Upvotes: 1

Related Questions