Attempt the HTTP request again only for specific status codes

When developing my Angular application, I encountered a situation where I needed to make an HTTP call to a backend server. To enhance its reliability, I decided to incorporate an interceptor to implement the retry pattern.

In the past, I utilized RxJS's retryWhen operator for this purpose. However, since it has been deprecated, I had to find an alternative approach:

return next.handle(copiedRequest).pipe(
  retry({
    count: 5,
    delay: 1000,
  }),
  catchError((error: HttpErrorResponse) => {
    if (error.status === 0) {
      // Server not responding, so handle accordingly
    }
    return throwError(() => error);
  })
);

Despite successfully implementing retries for all HTTP response statuses, I realized that there are scenarios where retrying based on certain status codes is unnecessary. Is there a way to introduce a filter to the retry logic in order to determine whether or not retry should be attempted?

Answer №1

To achieve what you're looking for, use the delay parameter of the retry operator:

next
  .handle(copiedRequest)
  .pipe(
    retry({
      count: 5,
      delay: (error: HttpErrorResponse, retryCount: number) => {
        // This is a demo and not utilized here, but you can customize the behavior based on retryCount
        
        switch (error.status) {
          case 0:
          case 1:
            return of(null);

          default:
            return throwError(() => error);
        }
      },
    })
  )

Check out this Stackblitz demo where you can interact and see how the original request is retried multiple times using mocks.

Look at the console output on Stackblitz:

Request made: 0 // first attempt
Request made: 1 // second attempt
Request made: 2 // third attempt
An error was caught: Error: Some mocked error // encountered a non-retryable error and forwarded it

Answer №2

Just like how Polly is used for retry mechanism in the .NET world, there's a handy tool known as cockatiel. With cockatiel, we can set up retries based on specific types of exceptions.

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

Leveraging Ionic 2 with Moment JS for Enhanced TimeZones

I am currently working on integrating moment.js with typescript. I have executed the following commands: npm install moment-timezone --save npm install @types/moment @types/moment-timezone --save However, when I use the formattime function, it appears th ...

What are some ways to determine if the current tab is the sender of a message in the Broadcast Channel API?

In my Angular application, I am looking to utilize the Broadcast Channel API to ensure that the logged-in state is maintained across different tabs. However, the tab where the user logs in requires a slightly different code execution compared to the othe ...

When using Angular's `createComponent()` method, an error may be thrown with the message "ERROR TypeError: Cannot add

I am currently working on a project where I am dynamically creating components. The component's class is being passed via an ngrx action and the process involves: loadComponent(componentType: Type<any>): void { const viewContainerRef = this.co ...

Decoding the HTML5 <video> tag using the html-react-parser library

I'm working on a NextJS V13 app where I need to display HTML content fetched from a CMS. Instead of using dangerouslySetHtml, I opted for the html-react-parser package to parse the HTML and replace certain embedded tags like <a>, <img>, an ...

Encountering a typescript error: Attempting to access [key] in an unsafe manner on an object of

I have recently developed a thorough equality checking function. However, I am encountering an issue with the highlighted lines in my code. Does anyone have any suggestions on how to rectify this problem (or perhaps explain what the error signifies)? Her ...

Is there a way to create a universal getter/setter for TypeScript classes?

One feature I understand is setting getters and setters for individual properties. export class Person { private _name: string; set name(value) { this._name = value; } get name() { return this._name; } } Is there a w ...

Issue: Directive parameter resolution failure

I've encountered an issue while trying to develop a directive npm package. Previously, I had successfully created packages for @Component, but this is my first attempt at creating one for @Directive. The problem arises when I run ng serve – the bu ...

Is there a way to remove the old React component when there are two instances of it still active while passing variables?

Recently, I've encountered some unusual behavior with my React component. As a newcomer to React, I have a page where users can configure toast notifications that are displayed. For this functionality, I'm utilizing the react-hot-toast package. U ...

Angular 2 is encountering issues with reading and displaying unicode characters (ud83dude31 or u0C28u0C3E) from the http response onto the user

My current task involves extracting unicode data from an http response, specifically for emojis. The response is in the form of a property-value pair within an object, with the message content being presented as JSON data ("messageContent":"hello \&bs ...

Tips for customizing the default name of the 'Page View' feature

After incorporating Angulartics2GoogleTagManager into the app.component, is it feasible to modify the default name of the tracked page view event from "Page View"? I require a different name than the current one. ...

Using optional chaining with TypeScript types

I'm dealing with a complex data structure that is deeply nested, and I need to reference a type within it. The issue is that this type doesn't have its own unique name or definition. Here's an example: MyQuery['system']['error ...

A guide on utilizing portals in Next.js to move a child element beyond its direct parent container

Current Setup Wrapper export const ContainerComponent = () => { return (<ChildComponent/>); } Child Component export const ChildComponent = () => { return ReactDOM.createPortal( <aside> <div>{"I am a c ...

Creating a versatile TypeScript Record that can accommodate multiple data types

I have a question regarding the use of Record in TypeScript. When I specify Record as the parameter type in a function, I encounter an error in my code because it does not allow different types. type Keys = 'name' | 'qty'; const getVal ...

Eliminate any unnecessary padding from elements in angular2 components

Is there a way to remove the automatic padding added to new components in angular2? I am facing this issue with the header of my project, as shown in the image below: https://i.sstatic.net/25Zpn.png I attempted to eliminate the padding by setting it to 0 ...

Ordering an array in Angular 2: A step-by-step guide

I am working on an Ionic 2 app with an older version of AngularJS that does not have the orderby pipe by default. As a result, I have an array structured like this: <div *ngFor="let boatBooking of boatBookings" style="padding: 0px; margin:0px;"> ...

Tips on optimizing data processing for quicker display with ngFor

I am currently facing an issue with loading a JSON file containing 3500 data. The data appears very slowly on the view, causing the application to work sluggishly. Below is a snippet of the JSON: export class Service { private items = new Arr ...

Enhance the annotation of JS types for arguments with default values

Currently, I am working within a code base that predominantly uses JS files, rather than TS. However, I have decided to incorporate tsc for type validation. In TypeScript, one method of inferring types for arguments is based on default values. For example ...

SystemJS could not locate the root directory for RxJS

There seems to be an issue with SystemJS loading rxjs modules on Windows, as it throws a 404 Not Found error on the rxjs directory. This problem does not occur on OSX, and all modules are up to date. GET http://localhost:8080/node_modules/rxjs/ 404 (Not F ...

Issue with redirecting to another link in Angular routing

After numerous attempts, I finally managed to configure the adviceRouterModule correctly. Despite extensive research and Google searches, I couldn't quite crack it. Here is the configuration for my AdviceRoutingModule: const adviceRouters: Routes = ...

Ways to switch up the titles on UploadThing

Recently, I started working with the UploadThing library and encountered a situation where I needed to personalize some names within the code. Here is what I have so far: Below is the snippet of code that I am currently using: "use client"; imp ...