reza
reza

Reputation: 6358

How to handle errors from HTTP observables

I am not sure how to handle http errors in an angular2 observable. What I have is

    getContextAddress() : Observable<string[]> {
        return this.http.get(this.patientContextProviderURL)
        .map((res:Response) => {
            return res.json()
        })
        .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}

in valid URL cases, i.e. response of 200, all is well. I am not sure why when I use a bad url, response code of 400, there is no error generate.

How do I handle that case?

Upvotes: 0

Views: 92

Answers (2)

reza
reza

Reputation: 6358

I was not catching the error where the subscription was taking place. My mistake

Upvotes: 0

DeborahK
DeborahK

Reputation: 60596

This code is simply re-throwing the error. Are you catching it somewhere?

For example, I have code like this:

this.productService.getProducts()
    .subscribe(products => this.products = products,
               error => this.errorMessage = <any>error);
}

This catches the thrown error and sets an errorMessage property that I then display in the UI.

Upvotes: 1

Related Questions