Facing the issue once more - Angular displaying "Http failure response for... 0 Unknown Error"

I have been researching extensively on this issue, particularly on Stack Overflow. Many of the responses point to it being a CORS problem, but I am uncertain if that is the case in my situation. Therefore, I am reaching out for help once again and would greatly appreciate any serious assistance.

I am currently developing an Angular application that accesses an API every 60 seconds on a web browser of an Android tablet. Initially, the app functions perfectly fine. However, after a few hours, I start encountering errors:

0-Http failure response for https://theurl.com/api/: 0 Unknown Error

The concerning aspect is that these errors occur randomly; sometimes they appear after 8,9, or 10 hours, other times after a full day, making it difficult for me to troubleshoot effectively. Nevertheless, when I reload the app, it starts working normally again. Unfortunately, I do not want to rely on manual reloading each time an error pops up, and I am struggling to identify the root cause of the issue.

I was considering implementing a logic in the interceptor to automatically reload the app whenever it encounters an error status of 0. However, I am unsure if this approach is considered best practice...

Any suggestions or workarounds would be highly appreciated. Thank you!

// Edit: I have decided to implement a mechanism where the app will stop retrying after encountering error status 0 five times:

 intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<
    | HttpSentEvent
    | HttpHeaderResponse
    | HttpProgressEvent
    | HttpResponse<any>
    | HttpUserEvent<any>
    | any
  > {
 return next.handle(request).pipe(
        catchError(err => {
          if (err instanceof HttpErrorResponse) {
            switch (err.status) {
              case 401:
                return this.handle401Error(request, next);
              case 0:
                return this.handleUnknownError(request, next);
              default:
                return this.router.navigate(['system-error']);
            }
          } else {
            return throwError(err);
          }
        })
      );
    }
   }

     private handleUnknownError(request: HttpRequest<any>, next: HttpHandler) {
        return next.handle(request).pipe(
          retryWhen(errors => {
            return errors.pipe(delay(2000), take(5));
          })
        );
      }

Answer №1

Issue 0 may be due to your outbound request being unable to depart. This could be a result of CORS or certain security measures preventing the request from going through, a service worker intercepting and failing to process the request, or the device's internet connection encountering failure or suspension.

I have encountered this issue in several of my own projects, attributing it to the device entering standby mode or suspending its own connection to conserve power. To troubleshoot whether the device's internet connection is the root cause, you can enable and monitor the HTTP ProgressEvents coming from the observable (failed internet connection):

These errors display status 0 and contain an error property with a ProgressEvent object that potentially offers additional insights. https://angular.io/guide/http#getting-error-details

While I cannot definitively address your query, I hope this provides another avenue for exploration. I would appreciate hearing if this proves beneficial.

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

Angular: Attempting to coordinate communication between two functions within my service

I have two separate functions but I would like them to sync up and work together. The first function is called getRandomNumbers - its role is to display a random number between 1 and 20 every second. The second function is up - it's a button that al ...

Trigger @HostListener event after a certain delay

I am currently working on implementing a basic infinite-scroll directive in Angular2. To achieve this, I am utilizing @HostListener('window:scroll') to capture the scroll event and extract the data from the $target. My concern is that every time ...

Creating a custom styled-component in Typescript for rendering {props.children}

One of my components is called ExternalLink which is used to display anchor tags for external URLs. This component has been styled using styled-components. Check out the CodeSandbox demo here ExternalLink.tsx This component takes an href prop and render ...

Developers beware: A functional component is generating a warning during development. Remember, function components do not support refs. Perhaps you intended to utilize React.forwardRef

Hey there! I have a question about a plugin that I've created and integrated into an application called HRnet (React 18). During development, I'm not encountering any warnings on the plugin side. However, when developing on the application side, ...

Ways to verify the identity of a user using an external authentication service

One of my microservices deals with user login and registration. Upon making a request to localhost:8080 with the body { "username": "test", "password":"test"}, I receive an authentication token like this: { "tok ...

Angular Migration - Unable to locate a suitable version

I need to upgrade my application from Angular 10 to Angular 11. However, during the migration process, I encountered the following error: npm ERR! code ETARGET npm ERR! notarget No matching version found for @ruf/<a href="/cdn-cgi/l/email-protection" cl ...

Retrieving the value that is not currently selected in a mat-select component

In my mat-table, there is a mat-select component displayed like this: <mat-select multiple placeholder="{{element.name}}" [(value)]="selectedCol" (selectionChange)="selectionChange($event)" [disabled]="!selection.isSelected(element.id)"> & ...

Issues with NgFor directive not functioning properly within a Bootstrap class in Angular 6

In my Angular project, I have successfully implemented a REST service. The film data is displayed as a JSON object below the image. However, I am facing an issue with printing the results inside the boxes using ngIf. Strangely, it works fine with ngFor exc ...

Angular-4: Exploring Component Reference on Click Event

One of my challenges involves dynamically adding different components when the user clicks, allowing them to add and remove any component. However, I am struggling to figure out how to reference the component where the user clicked in Angular-4. here are s ...

Can someone explain why the Next 13 API route is showing up as empty?

I am currently working with Next 13 and I am attempting to create a simple API route. My goal is to have a: "hi" returned when I visit localhost:3000/api/auth. Despite not encountering a 404 error or any errors in the terminal or console, I can&a ...

Encountering TS 2732 error while attempting to incorporate JSON into Typescript

Having trouble importing a JSON file into my TypeScript program, I keep getting error TS2732: Can't find module. The JSON file I'm trying to import is located in the src folder alongside the main.ts file. Here's my code: import logs = requi ...

Making an Angular 6 HTTP GET call using HTTP-Basic authentication

When attempting to access a URL that requires Basic Authentication, and returns JSON data, what is the proper way to include my username and password in the following HTTP request? private postsURL = "https://jsonExample/posts"; getPosts(): Observable& ...

Is there a way to utilize const assertions to retrieve the explicit types from objects nested at various levels?

In reference to this question, the previous structure had a depth of 2: const grandkids = { Karen: { Ava: ['Alice', 'Amelia'], Emma: ['Sarah'], }, Mary: { Sophia: ['Grace'], }, } as const; To ext ...

Creating TypeScript models from a JSON response in React components

My Angular 2 application retrieves a JSON string, and I am looking to map its values to a model. According to my understanding, a TypeScript model file is used to assist in mapping an HTTP Get response to an object - in this case, a class named 'Custo ...

Instantiate the component array upon object instantiation

I'm currently in the process of learning Angular 2, so please bear with me if this question seems trivial. I am attempting to create a dynamic form that can be bound to a model. However, I am encountering an issue where I am unable to initialize my ar ...

The Excel file fails to accurately interpret the date after being extracted from a zip folder

When uploading a zip folder containing an Excel file through the UI, I implemented the following code snippet: getZipData(file: File) { const jsZip = require('jszip'); let excelRecord: any[] = []; let images: { path: string, image: string }[] = [ ...

Cross-origin resource sharing problem (Backend developed in Express, Frontend in Angular)

I am currently utilizing Angular for my front-end development and Express for the back-end. I encountered a CORS issue with one of multiple API endpoints that have similar configurations: Failed to load http://localhost:3000/api/deletePost: No 'Acc ...

Learn how to dynamically adjust context using a server-client architecture with TRPC

Currently, I am referring to the tRPC documentation for guidance on creating a server side caller. But I'm facing a challenge in dynamically setting the value when incorporating it into my NextJS 13 pages. In my context.ts file, you will find the fol ...

Error encountered numerous times within computed signals (angular)

I have incorporated signals into my Angular application. One of the signals I am using is a computed signal, in which I deliberately introduce an exception to see how it is handled. Please note that my actual code is more intricate than this example. pu ...

Angular Service Singleton Utilized in Components

I have a structural question regarding my Angular application. I am following the widely-used core, shared, and feature modules structure, similar to the one found here. In my core module, I have a singleton notification service defined, but I use a custom ...