Can I catch certain errors before “subscribe()” in an RXJS observable in Angular2?

Is it possible for a base class to catch certain errors before allowing the subclass to subscribe to the observable in Angular2.

e.g.

export class SomeBaseClass {
    constructor(private _http: Http, private _location: Location) {}

    protected _fetchData(url): Observable<any> {
        const headers = new Headers();
        headers.append('Authorization', 'Token foo');
        return this._http.get(url, {headers})
            .map(response => response.json())
            .catch(response => this._handle401(error));
    }

    private _handle401(response: Response) {
        if(response.status === 401) {
            this._location.go('/login');
        }

        // What should this return?
    }
}

export class SomeClass extends SomeBaseClass {
    constructor( _http: Http,  _location: Location) {
        super(_http, _location);
    }

    doTheThing() {
        this._fetchData('/someUrl')
            .subscribe(
                response => this._handleResponse(response),
                error => this._handleErrorThatIsNot401(error));
    }

    private _handleResponse(response) {
        // ...
    }

    private _handleErrorThatIsNot401(error) {
        // ...
    }
}

Is catch what I am looking for? Should I be using map (or something else)? Or am I going about this the wrong way entirely?

Update

Both answers (so far) put me on the right track, ultimately – I solved it like this:

protected _get(url: string, data?: any): Observable<any> {
    return super._get(url, data, this._authorizationHeader)
        .map(response => response.json())
        .catch(response => this._handle401(response));
}

private _handle401(response: Response): Observable<any> {
    try {
        if(response.status === 401) {
            this._router.navigateByUrl('/login');      
            return Observable.throw(response.status);  
        }
    } catch(err) {
        console.warn('AuthenticatedHttpService._handle401');
        console.error(err);
    }

    return Observable.of(response);
}

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

.catch() is the right one.

Observable is lazy, so there are no errors before you subscribe. Not sure if you mean this kind of “before” therefore I mention it just to be sure.

Jason
Guest

Using catch alone does not help much since you have client code subscribed and you must return Observable from catch.

I would implement it as follows:

Rx.Observable.of(42)
.do(v=>{throw new Error('test')})
.catch(Rx.Observable.of(undefined))
.filter(v=>{return v !== undefined})
.subscribe(
(e)=>{console.log('next', e)}, 
(e)=>{console.log('error', e)}, 
()=>{console.log('complete')}
);