30

I had this code

    return this.http.get(this.pushUrl)
        .toPromise()
        .then(response => response.json().data as PushResult[])
        .catch(this.handleError);

I wanted to use observable instead of Promise

how can i return the error to the calling method?

What's the equivalent to Promise.reject ?

    doSomeGet() {
        console.info("sending get request");

        this.http.get(this.pushUrl)
            .forEach(function (response) { console.info(response.json()); })
            .catch(this.handleError);
    }

    private handleError(error: any) {
        console.error('An error occurred', error);
        // return Promise.reject(error.message || error);
    }
}

the calling method was:

getHeroes() {
    this.pushService
        .doSomeGet();
        // .then(pushResult => this.pushResult = pushResult)
        // .catch(error => this.error = error);
}
Elad Benda
  • 35,076
  • 87
  • 265
  • 471
  • The above code with ``Promise.reject`` uncommented works perfectly fine. I am not sure why. Do you have any thoughts on it? – raj Nov 15 '16 at 22:39

3 Answers3

35
private handleError(error: any) {
    // previously 
    // return Observable.throw('Some error information');

    // now
    return throwError('Some error information');
}

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
24

With RxJS 6 Observable.throw() has changed to throwError()

Observable.throw(new Error());

// becomes

throwError(new Error());

Source: RxJS v5.x to v6 Update Guide - Depracations

MHX
  • 1,581
  • 2
  • 21
  • 31
0

With RxJS 7 throwError(error: any) was marked obsolete due to be removed in v8

throwError(new Error());

// becomes

throwError(() => new Error());

Source: RxJS 6.x to 7.x

Kent Bair
  • 1
  • 1
  • 1