npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

apollo-link-error

v1.1.13

Published

Error Apollo Link for GraphQL Network Stack

Downloads

1,771,903

Readme


title: apollo-link-error description: Handle and inspect errors in your GraphQL network stack.

Use this link to do some custom logic when a GraphQL or network error happens:

import { onError } from "apollo-link-error";

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

Apollo Link is a system of modular components for GraphQL networking. Read the docs to learn how to use this link with libraries like Apollo Client and graphql-tools, or as a standalone client.

Callback

Error Link takes a function that is called in the event of an error. This function is called with an object containing the following keys:

  • operation: The Operation that errored
  • response: The result returned from lower down in the link chain
  • graphQLErrors: An array of errors from the GraphQL endpoint
  • networkError: Any error during the link execution or server response, that wasn't delivered as part of the errors field in the GraphQL result
  • forward: A reference to the next link in the chain. Calling return forward(operation) in the callback will retry the request, returning a new observable for the upstream link to subscribe to.

Returns: Observable<FetchResult> | void The error callback can optionally return an observable from calling forward(operation) if it wants to retry the request. It should not return anything else.

Error categorization

An error is passed as a networkError if a link further down the chain called the error callback on the observable. In most cases, graphQLErrors is the errors field of the result from the last next call.

A networkError can contain additional fields, such as a GraphQL object in the case of a failing HTTP status code from apollo-link-http. In this situation, graphQLErrors is an alias for networkError.result.errors if the property exists.

Retrying failed requests

An error handler might want to do more than just logging errors. You can check for a certain failure condition or error code, and retry the request if rectifying the error is possible. For example, when using some form of token based authentication, there is a need to handle re-authentication when the token expires. Here is an example of how to do this using forward().

onError(({ graphQLErrors, networkError, operation, forward }) => {
    if (graphQLErrors) {
      for (let err of graphQLErrors) {
        switch (err.extensions.code) {
          case 'UNAUTHENTICATED':
            // error code is set to UNAUTHENTICATED
            // when AuthenticationError thrown in resolver

            // modify the operation context with a new token
            const oldHeaders = operation.getContext().headers;
            operation.setContext({
              headers: {
                ...oldHeaders,
                authorization: getNewToken(),
              },
            });
            // retry the request, returning the new observable
            return forward(operation);
        }
      }
    }
    if (networkError) {
      console.log(`[Network error]: ${networkError}`);
      // if you would also like to retry automatically on
      // network errors, we recommend that you use
      // apollo-link-retry
    }
  }
);

Here is a diagram of how the request flow looks like now: Diagram of request flow after retrying in error links

One caveat is that the errors from the new response from retrying the request does not get passed into the error handler again. This helps to avoid being trapped in an endless request loop when you call forward() in your error handler.

Ignoring errors

If you want to conditionally ignore errors, you can set response.errors = undefined; within the error handler:

onError(({ response, operation }) => {
  if (operation.operationName === "IgnoreErrorsQuery") {
    response.errors = undefined;
  }
});