Kay
Kay

Reputation: 19640

How to get/log/capture the errors from a graphql apollo client query

I am interfacing with a graphql backend using the @apollo/client.

The request i am making returns a 400 bad request and in the network tab i can see the json of the errors.

This is what i would like to log in my code but i am uanble to.

enter image description here

        try {
            const response = await GraphQLClient.query({
                query: GET_PERSON,
                variables: {
                    personId: id,
                },
                errorPolicy: "all",
            });
            console.log("response", response);
        } catch (err) {
            console.log("err", err);
        }

When i execute the above it goees into the catch block and i do not have access to the errors object.

err Error: Response not successful: Received status code 400 at new ApolloError (index.ts:54) at QueryManager.ts:1073 at both (asyncMap.ts:30) at asyncMap.ts:19 at new Promise () at Object.then (asyncMap.ts:19) at Object.error (asyncMap.ts:31) at notifySubscription (module.js:137) at onNotify (module.js:176) at SubscriptionObserver.error (module.js:229) at iteration.ts:13 at Array.forEach () at iterateObserversSafely (iteration.ts:13) at Object.error (Concast.ts:185) at notifySubscription (module.js:137) at onNotify (module.js:176) at SubscriptionObserver.error (module.js:229) at createHttpLink.ts:203

graphqlservice

import { ApolloClient, InMemoryCache } from "@apollo/client";
import { Config } from "./../config";

const FRONTEND_API = `${Config.frontend_api}/graphql` || "";

export const GraphQLClient = new ApolloClient({
    uri: FRONTEND_API,
    cache: new InMemoryCache(),
}

Upvotes: 1

Views: 3016

Answers (1)

Kay
Kay

Reputation: 19640

To get the errors as a json response in the catch method.

console.log(err.networkError.result.errors);

Still very unsure why the response object has an error and errors property and i don't know when these are accessible, maybe someone else could shed some light on that.

export declare type ApolloQueryResult<T> = {
    data: T;
    errors?: ReadonlyArray<GraphQLError>;
    error?: ApolloError;
    loading: boolean;
    networkStatus: NetworkStatus;
    partial?: boolean;
};

Upvotes: 1

Related Questions