Dealing with errors within nested requests while using switchMap with RxJS

I am faced with a situation where I need to make 2 dependent API calls: the getCars call requires the user id obtained from getUser.

There is a possibility that a user may not have any cars, resulting in a 404 error from the API.

How can I handle this scenario by returning the aggregated response, and when no cars are returned, simply using null/undefined for userData.cars?

I attempted to use catchError in the pipeline of getCars, but it doesn't seem to be effective:

getUser().pipe(
      switchMap(user => user.creditScore > 70 ? 
        getCars(user.id).pipe(
          catchError(() => of(undefined)),
          map( cars => ({user, cars}) )
        )
       : of({user: user, cars: undefined)
      )
    ).subscribe((userData) => {
      if (userData.user) {
        ........
      }
      if (!!userData.cars) {
        .........
      }
    },
    err => {
      ......
    });

Answer №1

Ensure that all paths in your code return or throw something within the catchError block. Additionally, make use of the rxjs of operator to return your default value as an observable. Here is the corrected code snippet:

getUser().pipe(
  switchMap(user => getCars(user.id).pipe(
    catchError((error) => {
      if (error.status == 404) return of([]);
      else throw error;
    }),
    map(cars => ({user, cars}))
  ))
).subscribe(res => ..., err => ...);

If a user has cars, the value of res will be:

{
  user: { id: 1 },
  cars: [ { id: 1 }, { id: 2} ]
}

If a user does not have any cars (due to a 404 error from getCars), the value of res will be:

{
  user: { id: 1 },
  cars: []
}

In the event of an unexpected error occurring in getCars (e.g., a 401 error), the error will be raised and can be accessed through err inside the subscribe method.

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

How to Properly Retrieve an Array of JSON Objects Using Ionic 3 Storage

Storing and retrieving an array of JSON objects locally with Ionic storage: Country[5] 0: {record_id: "1", local_TimeStamp: "16:00:00", country: "USA"} 1: {record_id: "2", local_TimeStamp: "17:00:00", country: "Japan"} 2: {record_id: "3", local_TimeStamp: ...

Maintain synchrony of the state with swiftly unfolding occurrences

I developed a custom hook to keep track of a state variable that increments based on the number of socket events received. However, when I tested by sending 10 simultaneous events, the total value of the state variable ended up being 6, 7, or 8 instead of ...

Typescript Angular2 filtering tutorial

In Angular 2 using TypeScript, the goal is to search for matching values from an array within an object array. The intention is to filter out any objects where the 'extraService' property contains any of the values from the 'array_values&apo ...

Angular 2: Emptying input field value on click event

I am experiencing an issue with resetting my input values. I have a search bar with filter functions. When I enter a value, it displays a list below and I want to add a function to these links. When I click on one of them, it takes me to another component ...

Tips for preventing the rxjs error "TypeError: Cannot read properties of undefined" in the Angular framework

When I try to open the page in Angular, I encounter this error: core.mjs:6485 ERROR TypeError: Cannot read properties of undefined (reading 'getDocumentContent') In my Angular component, I have an observable like this: selectedDocument$ = this.s ...

Experiencing a strange response while attempting to parse the result of an Angular 2 HTTP JSON request

After successfully implementing the http.get call and retrieving data from the request, I encountered an issue: this.http.get('https://data.cityofnewyork.us/resource/xx67-kt59.json').subscribe(data => { // Read the result field from the ...

Experiencing a problem with updating records in angular?

angular version: Angular CLI: 9.0.0-rc.7 I have encountered an issue while trying to update a record. After clicking on the edit icon, I am able to make changes to the record in the form. However, when I click on the Edit Button, the record gets updated i ...

Updating the active tab in the navigation bar whenever the router navigates

I'm struggling with changing the active tab in Angular 2 and Bootstrap 4. I have managed to get the active tab to change using this code snippet: navbar.component.html <nav class="navbar navbar-fixed-top navbar-light bg-faded"> <button cl ...

Validation of passwords containing special characters in Angular2

I am working on setting up password validation requirements to ensure the field contains: Both uppercase letters, lowercase letters, numbers and special characters This is my current progress: passwordValueValidator(control) { if (control.value != u ...

Describing a function in Typescript that takes an array of functions as input, and outputs an array containing the return types of each function

Can the code snippet below be accurately typed? function determineElementTypes(...array: Array<(() => string) | (() => number) | (() => {prop: string}) | (() => number[])>) { /// .. do something /// .. and then return an array ...

Using renderProps in combination with TypeScript

I've encountered an issue while trying to convert my React project to TypeScript, specifically with the login component that uses react-google-login. The error I'm facing is related to renderProps: Overload 1 of 2, '(props: { component: El ...

The application's user interface is currently unable to access the REST API of the SSO Server

In the Angular front end, we are encountering an issue where it cannot call the REST API of the SSO server in the customer's environment to retrieve the open-id configuration. There doesn't seem to be any network calls being made when checked in ...

In Typescript, it is possible to provide values other than undefined for a parameter that is

I experimented with the code below in TypeScript Playground with all settings enabled. My expectation was that the TS compiler would only allow the first call() to be valid. However, to my surprise, all four calls were accepted. Upon inspecting the calls, ...

What is the best way to kickstart a Reactive Angular 2 form by utilizing an Observable?

My current strategy involves storing the form values in my ngrx store so that users can easily navigate around the site and return to the form if needed. The concept is to have the form values repopulate from the store using an observable. This is how I a ...

Avoiding the restriction of narrowing generic types when employing literals with currying in TypeScript

Trying to design types for Sanctuary (js library focused on functional programming) has posed a challenge. The goal is to define an Ord type that represents any value with a natural order. In essence, an Ord can be: A built-in primitive type: number, str ...

Adding TypeScript to your Vue 3 and Vite project: A step-by-step guide

After setting up my project by installing Vue and Vite using the create-vite-app module, I decided to update all the packages generated by 'init vite-app' to the latest RC versions for both Vue and Vite. Now, I am interested in using TypeScript ...

Angular 4 Query Building Plugin

Looking for a query builder plugin compatible with Angular 4 to create nested queries in my project. Some options I found include: https://www.npmjs.com/package/angular2-query-builder (Requires Angular 4+ ) (For AngularJS) (For Angular JS). The c ...

What are the recommended techniques for utilizing prototypal and prototype-based inheritance in modern JavaScript (ES6) and TypeScript?

Some older discussions on Javascript prototypal inheritance & delegation can be found below: Benefits of prototypal inheritance over classical? classical inheritance vs prototypal inheritance in javascript I am curious about the current (2018) recom ...

receiving feedback from Firebase push action

I have a method to add a new entry in Firebase Realtime Database like so: assignGiftCard(email:string, type: string, value: number, code:string){ let giftCard = { "type" : type, "value": value, "code": code } this.db.list(& ...

Customize the appearance of the Material UI expansion panel when it is in its expanded

Is there a way to customize the height of an expanded expansion panel summary? Specifically, I am looking to remove the min-height property and set the summary panel's height to 40px instead of the default 64px. I have attempted to make this change in ...