简体   繁体   English

可观察的Promise错误未调用catch

[英]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. 我使用@ angular / http进行http调用(可观察),并使用NativeStorage库进行Promise存储机制。 That's why I use FromPromise to convert Promise funtion "NativeStorage.getItem("xxx")" to Observable. 这就是为什么我使用FromPromise将Promise功能“ NativeStorage.getItem(” xxx“)”转换为Observable的原因。

I am even not sure if this is a good practice and the chain is broken at the line "console.log("HIT SUCCESSFULLY");" 我什至不确定这是否是一个好习惯,并且在“ 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. 由于存储中没有名为“ externalAccessToken”的项目,因此在Promise中捕获异常null是正常的,但是我不明白为什么它在此之后停止执行。

Till now, I have tried to return something else other than null and using "Promise.reject()" which caused "Unhandled Promise rejection" error. 到现在为止,我尝试返回除null之外的其他内容,并使用“ Promise.reject()”返回了导致“未处理的承诺拒绝”错误。

How can I keep the the code executing and hit the catch function of Observable 我如何保持代码执行并点击Observable的catch函数

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; 我已删除Promise.catch并保留Observable.catch以便在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. Catch工作原理与编程中的try / catch完全相同。

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 / catch执行,您可以这样做:

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. 您将需要将该错误作为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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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