End the pipeline execution in a chain of RxJS observables

Here is a scenario where a series of Observables are chained together. Is it possible to prevent the subsequent chain from executing if an error is thrown by 'parentObs1'?

import { throwError } from "rxjs";
import { mergeMap, catchError } from "rxjs/operators";

const parentObs1 = throwError("parentObs1");
const childObs2 = throwError("childObs2");
const grandChildObs3 = throwError("grandChildObs3");

parentObs1
  .pipe(
    mergeMap(() => childObs2),
    catchError((error) => throwError("Error in Obs1 CatchError block"))
  )
  // How can we avoid running this pipe if the previous one throws an error?
  .pipe(
    mergeMap(() => grandChildObs3),
    catchError((error) => throwError("Error in Obs2 CatchError block"))
  )
  .subscribe(
    () => {},
    (error: any) => {
      console.log(error); // It is expected to print 'Error in Obs1 CatchError block' but currently displays 'Error in Obs2 CatchError block'
    }
  );

Answer №1

The second catchError function catches the initial error and then throws a new error, ensuring that only the second error message appears in your subscription.

In my opinion, it may not be necessary to use the catchError operators at all:

parentObs1
  .pipe(
    mergeMap(() => childObs2),
    mergeMap(() => grandChildObs3),
  )
  .subscribe(
    () => {},
    (error: any) => {
      console.log(error);
    }
  );

This way, your errors will go straight to your subscription without the need for additional processing.

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

The proper approach for managing downloaded d.ts files from DefinitelyTyped after installation through npm

Visual Studio 2017 Enterprise ASP.NET MVC Application TypeScript 2.5 SDK Source control is in TFS I have opted to use Microsoft's built-in property editor instead of creating a custom tsconfig.config file: To streamline my workflow, I rely on Mad&ap ...

Collaborative service involves objects passing through reference

I am encountering an issue with a shared service in angular. Upon application startup, the init function is triggered, fetching and returning data that is vital across the entire application. Components have the ability to inject this service and retrieve ...

Autocomplete search from a distance

I am currently learning Angular and trying to create an autocomplete form with content that is filtered on the back-end. I have defined a class and Interface for Terminal: export class Terminal { constructor( public id: number, public name: ...

When you click, you will be directed to the specific details of the object

I have a recipe component that displays a list of recipes from my database and a recipe-detail component that should show the details of a selected recipe. What I aim to achieve is that when someone clicks on a recipe name, they are routed to the recipe-de ...

Having trouble accessing functions in Typescript when importing JavaScript files, although able to access them in HTML

Recently, I started incorporating TypeScript and React into my company's existing JavaScript code base. It has been a bit of a rollercoaster ride, as I'm sure many can relate to. After conquering major obstacles such as setting up webpack correc ...

Utilize a Typescript library within a separate Typescript library

I have a TypeScript library on GitHub that I want to install using npm install --save git+ssh://<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f38362b1d15c3f4">[email protected]</a>:User/mylib.git into my targ ...

What is the best way to refresh a personalized form element using Angular?

I have developed a custom form control with validation that utilizes a standalone FormControl to manage the value and perform certain validations. Is there a method in Angular to reset the inner FormControl when the control is being reset from another For ...

The validation process in Redux forms

Imagine we have the following types defined: interface MyFormFields { FirstName: string; LastName: string; } type FieldsType = keyof MyFormFields; const field1: FieldsType = "c"; const field2 = "c" as FieldsType; Now, I am looking to implemen ...

Connect AngularFire to a specific object

I'm facing an issue with my Users.class where I need it to automatically map or bind after fetching data from Firebase. I've been trying to search for the right term but haven't found any information yet. import { Component, OnInit } from & ...

Why is my Angular promise unexpectedly landing in the error callback?

I am facing an issue with my Angular + Typescript client. I have developed a PHP API and need to send a post request to it. Upon receiving the request, the server fills the response body with the correct data (verified through server debugging). However, w ...

Remove the ability to select from the dropped list item

Here is the HTML and Javascript code I used to enable drag and drop functionality for list items from one div to another: HTML: <div class="listArea"> <h4> Drag and Drop list in Green Area: </h4> <ul class="unstyle"> & ...

Unexpected expression after upgrading to TypeScript 3.7.2 was encountered, file expected.ts(1109)

After updating TypeScript from version 3.6.x to 3.7.2, I started using optional chaining in my code. However, I encountered a peculiar error. Error message: Expression expected.ts(1109) This error appeared in both my (vim, VSCode) IDE, even though the ...

I am having trouble locating my source code within the Typescript module

My issue lies with a file called Server.js, which holds the code for export class Program and includes <reference path='mscorlib.ts'/>. However, when I compile it using the command: tsc -t ES5 Server.ts --module commonjs --out Server.js T ...

What is the best way to map elements when passing props as well?

In my code, I am using multiple text fields and I want to simplify the process by mapping them instead of duplicating the code. The challenge I'm facing is that these textfields also require elements from the constructor props. import React, { Compon ...

Return a potential undefined output

I am working with a variable called root which could potentially be undefined. Its value is only determined at runtime. const root = resolvedRoot || await this.fileSystem.getCurrentUserHome(); console.log('root.uri = ' + root.uri); The existenc ...

Is it possible to switch the hamburger menu button to an X icon upon clicking in Vue 3 with the help of PrimeVue?

When the Menubar component is used, the hamburger menu automatically appears when resizing the browser window. However, I want to change the icon from pi-bars to pi-times when that button is clicked. Is there a way to achieve this? I am uncertain of how t ...

What is the best way to invoke a TypeScript function within a jQuery function?

Is it possible to invoke a TypeScript function within a jQuery function? If so, what is the correct approach? Here is an example of my component.ts file: getCalendar(){ calendarOptions:Object = { height: 'parent', fixedWeekCount : ...

Tips for triggering functions when a user closes the browser or tab in Angular 9

I've exhausted all my research efforts in trying to find a solution that actually works. The problem I am facing is getting two methods from two different services to run when the browser or tab is closed. I attempted using the fetch API, which worke ...

I'm having trouble with implementing a basic show/hide feature for the login and logout options in the navigation bar using Angular. Can anyone help me figure out why it's

Is there a way to display the functionality after logging in without using session storage or implementing the logout function? The HTML for navigation is provided below. <nav class="navbar navbar-expand-sm navbar-light bg-light"> ...

What are the steps to setting up a basic Material UI Select component with React and Typescript?

I'm struggling to make the most basic Material UI Select work in React using Typescript. After spending three hours searching, I couldn't find an example that clearly explains how to set the label or placeholder for the Select component (I review ...