Mastering Angular Apollo Error Resolution Methods

Hey everyone, I'm facing a problem with apollo-angular and apollo-link-error that I just can't seem to figure out. I've experimented with different approaches but have had no luck catching errors on the client-side of my angular web app. Below are the attempts I've made. Any advice or fresh perspectives would be greatly appreciated.

Essentially, what I want to achieve is to notify users when an error occurs. If anyone knows of another npm package besides apollo-link-error that could help me accomplish this, I'm open to suggestions.

Attempt 1:

export class AppModule {
  constructor (apollo: Apollo, httpLink: HttpLink) {
    apollo.create({
      link: httpLink.create({
        uri: 'http://localhost:8080/graphql'
      }),
      cache: new InMemoryCache()
    });

    const error = onError(({ networkError }) => {
      const networkErrorRef:HttpErrorResponse = networkError as HttpErrorResponse;
      if (networkErrorRef && networkErrorRef.status === 401) {
        console.log('Prompt User', error);
      }
    });
  }
}

Attempt 2:

export class AppModule {
  constructor (apollo: Apollo, httpLink: HttpLink) {
    apollo.create({
      link: httpLink.create({
        uri: 'http://localhost:8080/graphql'
      }),
      cache: new InMemoryCache()
    });

    const error = onError(({networkError}) => {
      if (networkError.status === 401) {
        console.log('Prompt User', error);
      }
    });
  }
}

Attempt 3:

export class AppModule {
constructor (apollo: Apollo, httpLink: HttpLink) {
apollo.create({
  link: httpLink.create({
    uri: 'http://localhost:8080/graphql'
  }),
  cache: new InMemoryCache()
});

const link = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
      ),
    );
    if (networkError) console.log(`[Network error]: ${networkError}`);
  });
 }
}

Answer №1

When working with apollo-link-error, consider it as a middleware that needs to be integrated into the fetching process within the apollo client.

This entails creating a new apollo link that combines both the http and error links:

import { ApolloLink } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';
import { onError } from 'apollo-link-error';

...

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
      ),
    );
    if (networkError) console.log(`[Network error]: ${networkError}`);
  });
 }
}

const httpLink = new HttpLink({
   uri: "http://localhost:8080/graphql"
});

const httpLinkWithErrorHandling = ApolloLink.from([
   errorLink,
   httpLink,
]);

apollo.create({
  link: httpLinkWithErrorHandling,
  cache: new InMemoryCache()
});

...

Answer №2

Here is an alternative approach:

import { HttpLink } from 'apollo-link-http';
import { onError } from 'apollo-link-error';

...

const errorHandling = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
      ),
    );
    if (networkError) console.log(`[Network error]: ${networkError}`);
  });
 }
}

const newLink = httpLink.create({
  uri: environment.serverAPI.endpoint,
});

apolloClient.create({
  link: errorHandling.concat(newLink),
  cache: new InMemoryCache()
});

...

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

Is it possible to transfer the security measures from Angular 6 to Angular 9?

Is it necessary to update my Angular project from version 6 to 7 before moving on to the latest version, or can I upgrade directly to the most recent version of Angular? ...

UI-Router - issue with query parameters preventing arrays with only one item

My application utilizes UI-Router, specifically with a state named Widgets that includes a query parameter accepting an array of widgets: const widgetsState = { name: "widgets", url: "/widgets?{widgets:string[]}", component: Widgets, pa ...

Recovering the .angular/cache folder - a step-by-step guide

Recently, I went through the process of upgrading my Angular project from version 8 to version 17. While cleaning up, I ended up deleting the '.angular' folder as I noticed that my project's compilation time had increased after the upgrade. ...

Is there a way to transform an angular 2 app.module into ES6 format?

import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; //specific imports remov ...

Angular 14: Exploring the left datepicker panel navigation in PrimeNG

In my situation, I am trying to adjust the position of the date-picker in relation to a panel displayed within a <p-calendar> element. Due to a splitter on the right side, I need to shift the date-picker towards the left. Here is the HTML code: < ...

Are the missing attributes the type of properties that are absent?

I have a pair of interfaces: meal-component.ts: export interface MealComponent { componentId: string; componentQuantity: number; } meal.ts: import { MealComponent } from 'src/app/interfaces/meal-component'; export interface Meal { ...

Using Typescript to define custom PopperComponent props in Material UI

I'm currently utilizing the Material UI autocomplete feature in my React and Typescript application. I'm looking to create a custom popper component to ensure that the popper is full-width. Here's how I can achieve this: const CustomPopper ...

The attribute 'map' is not found on the data type 'Observable<[{}, {}]>'

Struggling to incorporate map, PublishReplay, and other rxjs functions into Angular6, I keep encountering a compilation error stating "Property 'map' does not exist on type 'Observable<[{}, {}]>'" every time. The same issue arises ...

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 ...

When working with Angular Universal, using d3.select may result in a "reference error: document is not defined" in the server.js file

I'm currently working on an Angular project that uses server-side rendering to generate D3 charts. Each chart is encapsulated within its own component, such as a line-chart component which consists of TypeScript, spec.ts, HTML, and CSS files for rende ...

Is there a way to invoke an Angular2 function from within a Google Map infowindow?

I am currently working on integrating Google Maps using javascript in a project, and I'm facing a challenge. I want to call an Angular2 function inside an infowindow as shown in the code snippet below. Pay attention to the infoContent variable that co ...

Guide on creating a server-side middleware in Next.js

In my upcoming nextjs project, which is a monorepo with both frontend and backend components, I am in need of a middleware to intercept requests. This middleware will handle tasks such as authentication and other necessary controls for every API call. Alth ...

Exploring Angular 2: Diving into Validators, ReactiveForms, FormBuilder, and tailored classes

If you have a class called User with properties username and password export class User { username = ''; password = ''; } To create a reactive form, you can use the following syntax this.userForm = this.fb.group({ usernam ...

What steps should I take to transition from using require statements to imports with typescript in my mocha tests?

I have the following values in my package.json file: "scripts": { "test": "mocha -r ts-node/register security.test.ts" }, "type": "module", . . ...

Having trouble rendering Next.JS dynamic pages using router.push()? Find out how to fix routing issues in your

The issue I am facing revolves around the visibility of the navbar component when using route.push(). It appears that the navbar is not showing up on the page, while the rest of the content including the footer is displayed. My goal is to navigate to a dy ...

The process of adding new files to an event's index

I'm trying to attach a file to an event like this: event.target.files[0]=newFile; The error I'm getting is "Failed to set an indexed property on 'FileList': Index property setter is not supported." Is there an alternative solution fo ...

Azure deployment of a proprietary npm package

As a developer with git integration for my Angular web site, I have successfully checked code into Git and deployed it to Azure. Everything was running smoothly until I encountered an issue when trying to pull a private npm package. It dawned on me that I ...

The @input field is failing to show the value entered by the user

I'm having trouble with my dynamic reactive form, as the value is not showing up <div *ngFor="let deliveryAcross of (deliveriesAcross | async)!; let i = index;"> <app-delivery-across [index]="i" [deliveryAcross]= ...

Error in Typescript: Unable to locate module with proper type declarations

Recently embarking on a new nodejs project with typescript, I utilized Typings (https://github.com/typings/typings) to install reference files for node v4.x and express v4.x. Outlined in my setup are the following versions: Node - v4.2.6 Typescript - v1 ...

Retrieve the attribute from the element that is in the active state

I'm facing a challenge in determining the active status of an element attribute. I attempted the following approach, but it incorrectly returned false even though the element had the attribute in an active state - (.c-banner.active is present) During ...