简体   繁体   中英

Promise Error in Observable not calling catch

I am using @angular/http for http calls (Observable) and NativeStorage library for storage mechanism which is Promise. That's why I use FromPromise to convert Promise funtion "NativeStorage.getItem("xxx")" to Observable.

I am even not sure if this is a good practice and the chain is broken at the line "console.log("HIT SUCCESSFULLY");" and stops executing the code.

Since there is no item called "externalAccessToken" in the storage, it is normal to catch the exception null in Promise but I don't understand why it stops executing after that.

Till now, I have tried to return something else other than null and using "Promise.reject()" which caused "Unhandled Promise rejection" error.

How can I keep the the code executing and hit the catch function of Observable

public getExternalAccessTokenFromStorage(): Observable<any> {
    let externalAccessTokenPromise = NativeStorage.getItem('externalAccessToken');
    let getExternalAccessTokenFromStorage: Observable<any> = Observable.fromPromise(externalAccessTokenPromise.then(x => x)
   .catch(() => {
        console.log("HIT SUCCESSFULLY");
        return null
   }));

    return getExternalAccessTokenFromStorage.map(x => {
        console.log("NOT HIT AT ALL");
        return x;
    }).catch(() => {
        console.log("NOT HIT AT ALL");
        return null;
    });
}



public getUserInfo(): Observable<StoredUserModel> {        
    //Get External Access Token From LocalStorage        

    return this.getExternalAccessTokenFromStorage().flatMap((x: IExternalAccessTokenBindingModel) => {
        return this.getAccessTokenFromStorage().flatMap((accessToken: AccessTokenModel) => {
            console.log("NOT HIT AT ALL");
            let headers = new Headers();
            headers.append("Authorization", "Bearer " + accessToken.access_token);
            headers.append("Content-Type", "application/json");
            let options = new RequestOptions({ headers: headers });
            var externalBindingModel = JSON.stringify(x);
            return this.http.post(this.baseUrl + '/api/Account/ExternalUserInfo', externalBindingModel, options).map((res: Response) => {
                //ADD USER INTO NATIVESTORAGE
                this.addUserIntoStorage(res.json());
                return res.json();
            });
        });
    }).catch(x => {
        return this.getAccessTokenFromStorage().flatMap((accessToken: AccessTokenModel) => {
            console.log("NOT HIT AT ALL");
            let headers = new Headers();
            headers.append("Authorization", "Bearer " + accessToken.access_token);
            let options = new RequestOptions({ headers: headers });
            return this.http.get(this.baseUrl + '/api/Account/UserInfo', options).map((res: Response) => {
                //ADD USER INTO NATIVESTORAGE
                let user: StoredUserModel = res.json();
                this.addUserIntoStorage(res.json());
                return user;
            });
        }).catch(error => {
            return null;
        });
    });
}

UPDATED QUESTION:

I have removed Promise.catch and keep Observable.catch in order to catch unhandled exception in Observable;

public getExternalAccessTokenFromStorage(): Observable<any> {
    let externalAccessTokenPromise = NativeStorage.getItem('externalAccessToken');
    let getExternalAccessTokenFromStorage: Observable<any> = Observable.fromPromise(externalAccessTokenPromise);

    return getExternalAccessTokenFromStorage.map(x => {
        return x;
    }).catch(() => {
        return null;
    });
}

And I get the following error;

在此处输入图片说明

Catch works exactly the same as the try / catch clasues in programming.

Give the following example:

try {
   throw new Error('bang');
} catch(ex) {
   // do nothing
}

console.log('I'm still reachable');

We can reproduce the above with observable like this:

let o = Observable.create((observer)=>{
     observer.error(new Error('bang'));
}).catch(()=>{ 
    // do nothing
});

o.subscribe(()=>{
   console.log('I'm still reachable');
});

If you want to catch and process an error, but then prevent code below from executing using try / catch you would do this:

try {
   throw new Error('bang');
} catch(ex) {
   // do some logic here
   throw ex;
}

console.log('I cannot be reached');

It's the same in observables. You have to re-throw the error or yield an observable that also fails.

let o = Observable.create((observer)=>{
     observer.error(new Error('bang'));
}).catch((ex)=>{ 
    // do some logic here
    return Observable.throw(ex);
});

o.subscribe(()=>{
   console.log('I cannot be reached');
});

The problem is that you're catching, but not handling the error. You will want to throw the error as an Observable.

public getExternalAccessTokenFromStorage(): Observable<any> {
    let externalAccessTokenPromise = NativeStorage.getItem('externalAccessToken');
    let getExternalAccessTokenFromStorage: Observable<any> = Observable.fromPromise(externalAccessTokenPromise);

    return getExternalAccessTokenFromStorage.map(x => {
        return x;
    }).catch((error: any) => 
        Observable.throw(error.json().error || 'Server error');
    );
}

You can then handle your response and error in the form of a promise:

this.getExternalAccessTokenFromStorage().subscribe(
  res => console.log(res),
  error => console.log(error));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM