Apollo-client: networkError does not return statusCode

Created on 7 Nov 2020  路  3Comments  路  Source: apollographql/apollo-client

I am trying to capture a 401 error but unfortunately, it seems like still not possible. I could not find any information about it in the doc as well

My implementation example looks like below

const errorLink = onError( ({ networkError }: ErrorResponse) => {
if (networkError && 'statusCode' in networkError &&
networkError.statusCode === 401
) {
// perform logout stuff
}
})

Most helpful comment

Hi @mazraara,

This is what I've used to get around that:

  const errorLink = onError((({ networkError }) => {
    if (networkError && (networkError as ServerError).statusCode === 401) {
      // Your logic here
    }
  }) as ErrorLink.ErrorHandler);

All 3 comments

Hi @mazraara,

This is what I've used to get around that:

  const errorLink = onError((({ networkError }) => {
    if (networkError && (networkError as ServerError).statusCode === 401) {
      // Your logic here
    }
  }) as ErrorLink.ErrorHandler);

Hi @mazraara,

This is what I've used to get around that:

  const errorLink = onError((({ networkError }) => {
    if (networkError && (networkError as ServerError).statusCode === 401) {
      // Your logic here
    }
  }) as ErrorLink.ErrorHandler);

Thanks @devkot , it worked as a charm. I am just wondering do you have any doc's I can refer to about the as syntax?

Btw this confused me because the Apollo Docs on Customizing response logic don't talk about the different types of networkError's and how to check them in TypeScript.

鈿狅笍 If you're writing this in TypeScript make sure to import the ServerError type.

import {ServerError} from "@apollo/client/link/utils"

@devivekw the as keyword is called a TypeScript Type Assertion which works like casting.
https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions

Was this page helpful?
0 / 5 - 0 ratings