What is the best way to generate a simulated API request in rxjs that triggers an error after a delay of 1 second?

Explore the code playground here => https://stackblitz.com/edit/playground-rxjs-f8xjsh

Hello there, I'm attempting to replicate a failed API Call scenario where the error value should be emitted at the subscribe() { Error: } section.

import { from, of, pipe, forkJoin, interval, AsyncSubject, BehaviorSubject,defer, Subject, timer, observable, throwError } from 'rxjs';
import { concatMap, map, mergeMap, zipWith, delay, tap, concatAll, concat, concatWith, switchMap, catchError } from 'rxjs/operators';

const apiCall = (callNumber, isError=false) => of('Api Call Result ' + callNumber).pipe(
  tap(_=>console.log('Making API Call ' + callNumber)),
  delay(1000),
  tap(_=> throwError(() => new Error('ERROR')))
);

apiCall(99,true).subscribe({
  next: x=>console.log(x),
  error: e=>console.log(e)
});

Currently, the error is not getting caught or logged. Any assistance would be appreciated.

Stackblitz Link => https://stackblitz.com/edit/playground-rxjs-f8xjsh

Answer №1

This code snippet serves as a practical demonstration, inspired by the insights shared by @JSmart523

const fetchDataFromApi = (requestNumber: number, hasError = false) =>
  of('Data from API request ' + requestNumber).pipe(
    tap((_) => console.log('Executing some tasks before')),
    delay(1000),
    switchMap((_) => {
      if (hasError) {
        throw new Error(`ERROR`);
      } else {
        return of(_);
      }
    })
  );

fetchDataFromApi(99, true).subscribe({
  next: (result) => console.log(result),
  error: (err: Error) => console.log(err.message),
});

Answer №2

tap executes a function and then sends out whatever it receives, without any alteration.

throwError is a feature that produces an observable result.

Therefore, someObservable.pipe(x) will give back an observable that generates an error if x is

  • map(() => { throw new Error('msg') })
    , or

  • switchMap(() => throwError('msg'))

... alternatively, you can easily generate a new observable with throwError('msg')) without needing to use pipe...

however, using tap(() => anything) won't modify what the observable emits.

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

Event triggered by clicking on certain coordinates

Just starting with @asymmetrik/ngx-leaflet and Angular, so this might be a beginner's issue... I'm working on an Angular.io (v5) project that incorporates the @asymmetrik/ngx-leaflet-tutorial-ngcli Currently, I'm trying to retrieve the coo ...

Property element does not exist in this basic TypeScript project

I'm diving into my initial TypeScript project and encountering an issue with the "style". I attempted to utilize style!, create an if(changeBackgroundColor){}, but without success. let changeBackgroundColor = document.querySelectorAll('[data-styl ...

An issue encountered with NSwag in TypeScript-Angular involving enum property names and DateTime data type

Encountering issues with generating enums and DateTime attributes using Nswag and OpenApi. First concern is regarding the Enums generation, aiming for a specific format like: export enum BillboardType { BB = 0, BB18 = 1, Direction = 2, Ban ...

Keep the code running in JavaScript even in the presence of TypeScript errors

While working with create-react-app and typescript, I prefer for javascript execution not to be stopped if a typescript error is detected. Instead, I would like to receive a warning in the console without interrupting the UI. Is it feasible to adjust the ...

Create a function with an optional argument when the type can be inferred as an empty object

Is there a way to enforce a function's argument to be required if it has keys in the inferred type, and optional if it does not exist or is an empty object? I've experimented with conditionals and overloads but have yet to find a solution. const ...

What is the most effective way to loop through a JSON object and apply filtering based on user input?

I am currently working with a dataset stored in a MongoDB database, and below is the format of the data. I have been looking for something similar to streams functionality in Java but haven't had any luck. Data from the Database: [ { &quo ...

Experiencing an issue when attempting to deploy Strapi CMS with TypeScript on Railway - encountering the error message: "Unable to locate module 'typescript'"

Issue with Deploying Strapi CMS in TypeScript to Railway Currently facing challenges while trying to deploy Strapi CMS written in TypeScript to Railway. Despite the availability of a JavaScript template, there's a lack of a specific TypeScript templa ...

Updating the color of specific buttons using ngFor in Typescript and Angular 8

I have successfully implemented a feature where text is displayed word by word using an ngFor directive. Within the ngFor loop, there is an if-else statement that determines whether each word should be displayed as a <span> or a <button>. Now, ...

Tips for widening a union data type in a different section?

Is there a way to expand on a union type from another module? Below is an example showcasing the need for this, but I encountered a ts(3200) error due to duplicate identifiers. The Core module @org/core defines a union type called OptionType: // Defined i ...

Connecting Angular modules via npm link is a great way to share common

Creating a project with a shared module that contains generic elements and components, such as a header, is my goal. This shared module will eventually be added as a dependency in package.json and installed through Nexus. However, during the development ph ...

Why isn't the real-time database updating properly?

addNewDevice(deviceId: string, fireId: string){ let Token: string; let UserId: string; let newlyAddedDevice: Device; return this.authSrv.userId.pipe(take(1), switchMap( userId => { UserId = userId; retur ...

Prettier mandates that single-line if-statements without curly braces must be written on the same line

Having recently delved into the EsLint documentation, I've adopted the curly rule set to warning for instances of multiple or nested rows of statements within conditionals. "rules": { "curly":["warn", "multi-or-nes ...

Change character casing automatically when typing in a snippet in Visual Studio Code

My current goal is to create a code snippet for Visual Studio Code using TypeScript. The snippet I have so far mirrors a typed word in this format: import { ${1:Name}Component } from './${1:name}.component'; When I type the word at place #1, it ...

What is the best way to retrieve specific values from an ng-bootstrap modal?

I am working on a website that includes an ng-bootstrap modal. This modal contains two <select> elements with dynamic items, allowing the user to click on two buttons. One button simply closes the modal and sets the value of the Reactive Form to new ...

Bringing a JavaScript function into a TypeScript file results in it being treated as a namespace

Trying to bring a vanilla JavaScript function into a TypeScript file within a React Native app has presented some challenges. The import process goes smoothly when working with JS, but switching to TS triggers the error message: Cannot use namespace &apos ...

What is the reason behind the error Generic indexed type in Typescript?

Here is a scenario where I have a specific generic type: type MapToFunctions<T> = { [K in keyof T]?: (x: T[K]) => void; }; It functions correctly in this instance: type T1 = { a: string }; const fnmap1: MapToFunctions<T1> = { a: (x: st ...

Creating a custom definition file for TypeScript

Currently, I am facing an issue with a third-party library that provides global functions similar to jQuery ($ .functionName()), but unfortunately there is no definition file available. Due to this, my attempt to write my own file has been unsuccessful as ...

Elucidate a crucial aspect within a broad context

It seemed like I had a good grasp on how to tackle this, but clearly there's a misstep somewhere. I'm aiming to create a function that acts as a typeguard; its main purpose is to ascertain whether an input is an object containing a specified key ...

Can anyone help me with coloring Devanagiri diacritics in ReactJS?

I am currently working on a ReactJS project and I have come across an issue. I would like for the diacritic of a Devanagiri letter to be displayed in a different color than the letter it is attached to. For example: क + ी make की I was wondering ...

What is the proper way to utilize the router next function for optimal performance

I want to keep it on the same line, but it keeps giving me errors. Is there a way to prevent it from breaking onto a new line? const router = useRouter(); const { replace } = useRouter(); view image here ...