Keeping an Rxjs observable alive despite encountering errors by simply ignoring them

I am passing some values to an rxjs pipe and then subscribing to them. If there are any errors, I want to skip them and proceed with the remaining inputs.

of('foo', 'bar', 'error', 'bazz', 'nar', 'error', 'car').subscribe(...)

This is what I have done:

async function failIfError(item: string) {
  if (item === 'error') throw new Error('HTTP 500'); // This is an error we cannot control
  return item;
}

of('foo', 'bar', 'error', 'bazz', 'nar', 'error', 'car')
  .pipe(
    concatMap((item) => failIfError(item)),
    catchError((error) => of(null))
  )
  .subscribe((val) => console.log('value:', val));

Stackblitz: https://stackblitz.com/edit/rxjs-pfdtrr?devToolsHeight=33&file=index.ts

This is the current output:

value: foo
value: bar
value: null

How can I modify this code so that it skips the error (returning null) and continues with the execution? So that the output appears as follows:

value: foo
value: bar
value: null
value: bazz
value: nar
value: null
value: car

Answer №1

A situation where an error is triggered by failIfError, the catchError function will return null and halt the process. To address this, it is recommended to employ the form operator within the concatMap function.

Here is the code snippet for reference:

of('foo', 'bar', 'error', 'bazz', 'nar', 'error', 'car').pipe(
        concatMap((item) => from(failIfError(item)).pipe(catchError((error) => of(null))))
      .subscribe((val) => console.log('value:', val));

The usage of from(failIfError(item)) will result in an Observable being returned, allowing you to manage errors using catchError.

Answer №2

Utilizing the iif operator proves to be quite effective in this scenario, as it allows you to seamlessly handle errors and ensure that the main observable keeps running.

of('apple', 'banana', 'error', 'orange', 'pear', 'error', 'kiwi')
  .pipe(
    concatMap((fruit) =>
      iif(
        () => fruit === 'error',
        throwError(() => new Error('HTTP 409')),
        of(fruit)
      ).pipe(
        catchError((err) => {
          return of(null);
        })
      )
    )
  )
  .subscribe((f) => console.log('result:', f));

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

Generating a hyperlink to a specific user ID within a data table

I'm facing an issue with the formatting of my simple table when trying to navigate to user.id. Is there a better approach to this or should I consider moving LinkToUser? All styling has been removed to avoid any conflicts. import styled from 'st ...

The image upload failed: the server could not locate the requested URL

I am completely new to working with Flask, and I'm currently in the process of creating a basic image uploading application. After comparing my code with various tutorials on how to build similar apps, it seems like everything is in place. However, w ...

Reinitializing the database with Cypress (postgresql)

When populating the database, I intentionally do it partially for certain tests. However, after completing all tests, I would like to reset the database in order to avoid any complications that may arise during the next populate process. How can I efficien ...

Angular tabs display the initial tab

I attempted to implement the Tabs feature from angular material by following the provided documentation. However, I encountered an issue where the first tab does not display upon page load; I have to manually click on it to view its content. For more info ...

What is the best way to eliminate the input range in a React date range picker?

Here is an image illustrating a date range picker: https://i.stack.imgur.com/pwKaI.png I am looking to remove the labels for days before today and starting from today in the date range picker. How can I achieve this? Below is my code snippet: class Better ...

Encountering a TS2739 error while retrieving data in an Angular service function

In my code, I have created a function to fetch objects from my dummy data and assign them to a variable. setData(key: string) { let dataChunk: ProductIndex = PRODUCTDATA.filter(a => {a.productId == key;}); this.ProductData = dataChunk; } The i ...

HTML elements generated dynamically do not possess any jQuery properties

I have implemented a draggable list of Div elements using jQuery. Here is the code: <div id="external-events"> <h4>List Of Staffs</h4> <div class="external-event" data-id="1">Name</div> //Draggab ...

JavaScript code to retrieve an image from an <img> tag's source URL that only allows a single request and is tainted due to cross-origin restrictions

I have an image displayed in the HTML DOM. https://i.stack.imgur.com/oRgvF.png This particular image (the one with a green border) is contained within an img tag and has a URL as its source. I attempted to fetch this image using the fetch method, but enc ...

Interactive div containing elements that cannot be clicked

http://codepen.io/anon/pen/zxoYBN To demonstrate my issue, I created a small example where there is a link button within a div that toggles another div when clicked. However, I want the link button to not trigger the toggle event and be excluded from the ...

Performing a function inside a JSON structure

I am dealing with a JSON object that contains a list of functions I need to access and run like regular functions. However, I'm struggling to figure out how to achieve this. Here is what I have attempted: Bootstrapper.dynamic = { "interaction": f ...

Activate function when list item is clicked

My goal is to execute a function when users click on the li elements in the snippet below without relying solely on onclick. For instance, clicking on the first li element (with a value of 1) should trigger a function where the value "1" is passed as an ar ...

Retrieve the current time of day based on the user's timezone

Currently, I am working with a firebase cloud function that is responsible for sending push notifications to my app. My main requirement is to send notifications only during the day time. To achieve this, I have integrated moment-timezone library into my p ...

Enhancing Material UI icons with a sleek linear gradient

Despite following the instructions in this post Attempting to incorporate a linear gradient into a MaterialUI icon, as per a comment's recommendation, I am unable to get it to work. I experimented with the idea that the icons could be considered text ...

Remove objects from an array if they share identical key values

I'm having trouble getting this to work. I have an array of objects that looks like this: let myCities = [ { value: 'Barcelona', code: 02342837492482347 }, { value: 'Rome', code: 28282716171819 }, { v ...

Create a dynamic calendar by integrating dates with Javascript and an HTML table

Recently, I decided to delve into web design again and embark on a challenging project for my father's baseball business. The main task at hand is creating a detailed calendar using HTML tables. After spending a considerable amount of time perfecting ...

Move the internal array pointer forward to the next record in order to apply the insertAfter function within the jquery code

As a new jQuery user, I'm attempting to develop a jQuery function using data provided by PHP. My goal is to arrange DIV elements in order of their values using insertAfter method. However, I seem to be encountering some difficulty in advancing the poi ...

What is the method for verifying a password in the login process when it has been hashed by bcrypt during registration?

Currently in the process of developing a signup and login page using Node.js with Pug, Mongoose, and bcrypt. I am encrypting and storing passwords in the database after registration or sign up. I'm facing an issue with the comparison function as it r ...

Error: The React Material-UI modal is encountering a type error where it cannot access the property 'hasOwnProperty' of an undefined value

Whenever I include a modal in one of my classes, I encounter this error. Error: Unable to access property 'hasOwnProperty' of undefined Here is a simple example where I am attempting to display a basic modal at all times. Any suggestions? I h ...

Exploring the process of incorporating a JavaScript library into an Angular project

I've encountered this issue before and know there are various workarounds available. I often search online for front-end design code to enhance the user experience of my projects, such as carousels, animations, and more. However, most of these project ...

Is there a way to dynamically change the source of an image based on different screen sizes using Tailwind CSS?

Currently, I am utilizing the next/Image component for setting an image and applying styling through tailwindcss. However, I have encountered a roadblock at this juncture. My Objective My goal is to dynamically change the src attribute of the image based ...