简体   繁体   中英

Handling errors in an async/await Angular HttpClient method

I am attempting to use an async/await pattern in order to handle a scenario that might be considered "callback hell" if implemented otherwise.

Here is an extremely dumbed down version of the code. The real code has about 5 conditional HttpClient calls based on the data from the first call (not my api...) which is the reason why I am using the async/await pattern in the first place.

async blah(): Promise<boolean> {
    try {
        let resp = await this.http.get("https://httpstat.us/500").toPromise();
        console.warn("you should not see this");

        // the real code will logically call the api multiple times based on conditonal data from resp
        // hence the attempted usage of async/await to avoid "callback hell"
        // blah() will eventually return an object.

        return true;
    }
    catch (err) {
        console.error("caught inside blah()");
        throw err;
    }
}

ionViewDidLoad() {
    this.blah().then(data => {
        console.warn('okokokok');
    }).catch(error => {
        console.error(error)
    });
}

What happens, I can see the call actually 500, but the code continues and the following is printed to the console:

polyfills.js:3 GET https://httpstat.us/500/ 500 (Internal Server Error)
main.js:927 you should not see this
main.js:940 okokokok

As you can see, it isn't catching the 500 (or any other http status I have tested with)

The device I am testing with is a Pixel 2 running P and the console data is coming from a Chrome device inspector session.

Any advice would be greatly appreciated.

** Edit: This is clearly an issue with the combination of ionic and angular... It should work...

** Edit: it turns out to 100% be an Angular issue... Not the framework itself but how an interceptor was implemented. I will leave this here instead of deleting the question in the rare case someone else requires it.

If i uderstood your question correctly, you want to do cascade calls, so you make the http request and based on the response you want to do another http call. If that is the case, then you should consider using switchMap operator:

this.http.get("https://httpstat.us/500").pipe( switchMap( result => { if(result.a === 5) { return this.http.get("some server api url"); } return return this.http.get("another server api url"); }) )

You handle the errors then in rxjs way.

See cascading calls

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