All files / src/errors ApolloError.ts

88.89% Statements 32/36
70.37% Branches 19/27
80% Functions 8/10
93.55% Lines 29/31
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 7011x 11x     11x 11x 11x 11x       35x   11x 76x 76x 26x 27x     27x     76x 51x   76x 76x   11x 11x   77x 77x 77x 77x 77x 76x     1x   77x 77x   11x                                                
import { GraphQLError } from 'graphql';
 
// XXX some duck typing here because for some reason new ApolloError is not instanceof ApolloError
export function isApolloError(err: Error): err is ApolloError {
  return err.hasOwnProperty('graphQLErrors');
}
 
// Sets the error message on this error according to the
// the GraphQL and network errors that are present.
// If the error message has already been set through the
// constructor or otherwise, this function is a nop.
const generateErrorMessage = (err: ApolloError) => {
  let message = '';
  // If we have GraphQL errors present, add that to the error message.
  if (Array.isArray(err.graphQLErrors) && err.graphQLErrors.length !== 0) {
    err.graphQLErrors.forEach((graphQLError: GraphQLError) => {
      const errorMessage = graphQLError
        ? graphQLError.message
        : 'Error message not found.';
      message += `GraphQL error: ${errorMessage}\n`;
    });
  }
 
  if (err.networkError) {
    message += 'Network error: ' + err.networkError.message + '\n';
  }
 
  // strip newline from the end of the message
  message = message.replace(/\n$/, '');
  return message;
};
 
export class ApolloError extends Error {
  public message: string;
  public graphQLErrors: GraphQLError[];
  public networkError: Error | null;
 
  // An object that can be used to provide some additional information
  // about an error, e.g. specifying the type of error this is. Used
  // internally within Apollo Client.
  public extraInfo: any;
 
  // Constructs an instance of ApolloError given a GraphQLError
  // or a network error. Note that one of these has to be a valid
  // value or the constructed error will be meaningless.
  constructor({
    graphQLErrors,
    networkError,
    errorMessage,
    extraInfo,
  }: {
    graphQLErrors?: GraphQLError[];
    networkError?: Error | null;
    errorMessage?: string;
    extraInfo?: any;
  }) {
    super(errorMessage);
    this.graphQLErrors = graphQLErrors || [];
    this.networkError = networkError || null;
 
    if (!errorMessage) {
      this.message = generateErrorMessage(this);
    } else {
      this.message = errorMessage;
    }
 
    this.extraInfo = extraInfo;
  }
}