How to catch Timeouts


#1

I’m working on an Ionic 2 application that makes calls to the backend. Because of the nature of the application it won’t be uncommon that the user has connection problems. Therefor I want to gracefully catch HTTP requests that are probably going to timeout.

I have this function in a service that sets a timeout on the observable of 5 seconds. If that timeout passes I want to show an alert to the user that he should check his connection. However, I don’t seem to be able to really catch this error and it always results in a “Runtime Error: A Time Out has occured”.

getData() {
    return Observable.create(observer => {
        this.http.get(this.basePath + '/data').map(res => res.json()).timeout(5000).subscribe(results => {
            observer.next(results);
        }, err => {
            observer.error(err);
        });
    });
}

Does anyone know how I can catch the timeout and handle it myself without a Runtime Error “crashing” the app?