Managing errors with async/await in an Angular HttpClient function

I have been experimenting with an async/await pattern to manage a complex scenario that could potentially result in "callback hell" if approached differently.

Below is a simplified version of the code. The actual implementation involves approximately 5 conditional HttpClient calls based on data from the initial call (not my api...), which is why I opted for the async/await pattern.

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

        // In the real code, there will be multiple API calls based on conditional data from 'resp',
        // hence the use of async/await to avoid callback nesting.
        // Eventually, 'blah()' will 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)
    });
}

When implemented, I can observe that the call actually results in a 500 error, but the code continues and the following messages are printed to the console:

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

As seen, the error status code (500 or any other tested status) is not being caught.

The testing device is a Pixel 2 running Android P, with console data retrieved through Chrome's device inspector session.

Any guidance or advice on this issue would be highly appreciated.

** Edit: It seems this is related to a combination of Ionic and Angular... It should technically work...

** Edit: Confirmed to be a 100% Angular issue... Not the framework itself but how an interceptor was set up. Leaving this question here in case others encounter a similar problem.

Answer №1

If you understand the scenario correctly, the objective is to execute multiple http requests in sequence where each subsequent call depends on the response of the previous one. To achieve this behavior, you can utilize the switchMap operator in your code:

this.http.get("https://httpstat.us/500").pipe(
  switchMap( response => {
    if(response.status === 200) {
       return this.http.get("another server api url");
    }
    return this.http.get("fallback server api url");
  })
)

Error handling can be efficiently managed using RxJS functionalities.

For detailed instructions on cascading calls with RxJS, refer to this guide

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the syntax for passing a generic type to an anonymous function in a TypeScript TSX file?

The issue lies with the function below, which is causing a failure within a .tsx file: export const enhanceComponent = <T>(Component: React.ComponentType<T>) => (props: any) => ( <customContext.Consumer> {addCustomData => ...

Angular's openLayers functionality makes it easy to add features to a vector source from an XMLHttpRequest

My inspiration came from the use of , where they utilize: vectorSource.addFeatures(vectorSource.getFormat().readFeatures(xhr.responseText)); However, in Angular using TypeScript, addFeatures expects Feature[] while vectorSource.getFormat().readFeatures ...

Is it possible to transform div containers into unique shapes?

I'm working on a design where I want to have two divs that resemble teeth, one on the top half of the page and the other on the bottom half. The concept is to make these mouth piece divs open and close as you scroll with the mouse, revealing the conte ...

jquery disable document manipulation function

I need to make some updates to a simple function that involves the current textarea. $(document).on("keydown", updated_textarea_var, function (e) { // do stuff }); To achieve this, I tried disabling the previous function and running a new one w ...

Error message: Error in jQuery: Object is required for Internet

I have a button that is designed to trigger the opening of a jQuery UI Dialog when clicked. Strangely, it works perfectly in FF3, FF4, Chrome, and IE8 with ChromeFrame, but fails to function in regular IE8. The error message displayed simply states "Object ...

Is it advisable to reset the redux store every time a new route is navigated to?

My application is built using Angular, and I utilize Redux with ngrx/store to manage the state of my application. Everything has been working well so far. However, as my application has grown in size, I have noticed the following: For each page or resour ...

Is there a way to implement this toolbar in Ionic Angular?

https://i.sstatic.net/sGd1o.png I am looking to replicate the toolbar shown in the image above using Ionic. As a beginner in Ionic development, I am finding it challenging to translate the design into code. I attempted to use a grid layout, but the varyin ...

"Creating varying lengths of time with useSpring: A Step-by-Step Guide

Is there a way for my component to have an animation that fully displays in 0.3s when my mouse enters, but disappears in 0.1s when my mouse leaves? Currently, with useSpring, I can only define one duration for both scenarios. How can I set different dura ...

Enhancing component and view functionality in Angular

Recently, I started working on Angular 11 and encountered a simple yet challenging question. Despite my best efforts, I have been unable to find a suitable answer. In an attempt to utilize Object-Oriented Programming (OOP) concepts within Angular, I create ...

Use Protractor to simulate Loss Connection by clearing LocalStorage in a Spec

Currently, I am utilizing the code window.localStorage.removeItem("name of localStorage variable you want to remove"); to eliminate two distinct localStorage Keys within a particular specification, and it is successfully removing them. Afterwards, I proce ...

How to Effortlessly Populate Cascading Dropdowns in ASP.Net MVC 5 using a Reusable

I am currently working on an ASP.Net MVC 5 application that has multiple edit pages. Each edit page consists of various input elements such as textboxes, checkboxes, and dropdowns. I want to implement a functionality where the values of one dropdown are ch ...

Encountering a TS2307 error while trying to import external modules into a TypeScript file

I recently added a new module using npm and now I'm trying to use it in my typescript file. npm install marker-animate-unobtrusive --save import SlidingMarker = require('marker-animate-unobtrusive'); Unfortunately, when I try to access th ...

Error: mangosse is not recognized

Node keeps throwing the error 'ReferenceError: mangoose is not defined' in my face. The culprit seems to be this line: const dogSchema = new mangoose.Schema({ I made sure to install mongoose using npm $ npm i mongoose Check out the code belo ...

My customized mat-error seems to be malfunctioning. Does anyone have any insight as to why?

Encountering an issue where the mat-error is not functioning as intended. A custom component was created to manage errors, but it is not behaving correctly upon rendering. Here is the relevant page code: <mat-form-field appearance="outline"> < ...

Is it possible to deactivate the onclick event following a successful ajax request?

I am looking to disable the onclick event after a successful ajax request. <div class="report_button" id="report_button" title="Reportthis" style="width:65px;height:15px;" onclick="reported_text(user_id,lead_id);">Report</div> This is the div ...

use ajax to dynamically append a dropdown menu

Currently working on creating a form that includes a dropdown menu populated with elements from a database. The challenge I'm facing is ensuring that once an element is selected from the dropdown, another one appears dynamically. My goal is to use AJA ...

In tsconfig.json, the compiler is not utilizing other tsconfig.json files when using the "extends"

I'm attempting to streamline my project by breaking up my tsconfig.json into separate files. I have one for the source files and another for the tests. However, when I utilize the extends field, it seems that only the base tsconfig.json is being utili ...

"Obtaining Data from Local Storage on a Different Page: A Step-by-

``How can I transfer JSON data stored in local storage from one page to another within the same domain? In MainPage.html, the "user" data is stored in local storage and displayed. However, when data is added in AddEmploye.html and then returning to MainPa ...

"Implementing AngularJS bidirectional data binding to dynamically link user inputs with corresponding fields

Having trouble automatically outputting data with angularJS. One of the great features of angular is two-way data binding, but I can't seem to bind input with a JSON file. What I want to achieve is if the user's input matches a key, the correspon ...

Utilizing Highcharts with NodeJS

Is anyone familiar with implementing Highcharts in Node.js? I am currently encountering a problem using [email protected]: var Highcharts = require('highcharts'), chart = Highcharts.chart(null, { series: [{ data: [1, 3, 2, 4 ...