Search code examples
error-handlingrxjspolling

rxjs throwing an error once http request returns a specific value


I did write an Observable which is polling an URL which completes once a specific value is returned.

private checkPairingStatus(paringModel: any): Observable<ResponseObject> {
    let data = { id: 1234 };
    return Observable
        .interval(2000)
        .switchMap(() => this.get<ResponseObject>('http://api/getstatus', data))
        .first(r => r.Status === 'success') // once our pairing is active we emit that
        .timeout(90000, Observable.throw(new Error('Timeout ocurred')));
        // todo: find a way to abort the interval once the PairingStatus hits the 'canceled' status.
}

This works pretty fine but I'm struggling on how to throw an exception once my respone for example hits the following status "r.Status === 'canceled'".

Thanks for any hint on that!

Regards Lukas


Solution

  • You can just use do() and throw an Error with whatever condition you need:

    return Observable
        .interval(200)
        .do(val => {
            if (val == 5) {
                throw new Error('everything is broken');
            }
        })
        .subscribe(
            val => console.log(val),
            err => console.log('Error:', err.message)
        );
    

    This prints to console:

    0
    1
    2
    3
    4
    Error: everything is broken
    

    In your case you'll want to test a condition such as r.Status === 'canceled' or whatever.