What's the observable equivalent to `Promise.reject`
Asked Answered
U

3

31

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);
}
Unmannerly answered 17/8, 2016 at 10:18 Comment(1)
The above code with Promise.reject uncommented works perfectly fine. I am not sure why. Do you have any thoughts on it?Recti
C
36
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()?

Carmencarmena answered 17/8, 2016 at 10:22 Comment(2)
this method seems to be deprecated in RXJS... prefer using the throwError operator: here the documentationBerne
this is deprecated.Smalt
H
25

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

Hephzipa answered 11/7, 2018 at 16:12 Comment(0)
L
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

Lodovico answered 20/1, 2023 at 18:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.