locatedError.js.flow 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // @flow strict
  2. import inspect from '../jsutils/inspect';
  3. import type { ASTNode } from '../language/ast';
  4. import { GraphQLError } from './GraphQLError';
  5. /**
  6. * Given an arbitrary value, presumably thrown while attempting to execute a
  7. * GraphQL operation, produce a new GraphQLError aware of the location in the
  8. * document responsible for the original Error.
  9. */
  10. export function locatedError(
  11. rawOriginalError: mixed,
  12. nodes: ASTNode | $ReadOnlyArray<ASTNode> | void | null,
  13. path?: ?$ReadOnlyArray<string | number>,
  14. ): GraphQLError {
  15. // Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface.
  16. const originalError: Error | GraphQLError =
  17. rawOriginalError instanceof Error
  18. ? rawOriginalError
  19. : new Error('Unexpected error value: ' + inspect(rawOriginalError));
  20. // Note: this uses a brand-check to support GraphQL errors originating from other contexts.
  21. if (Array.isArray(originalError.path)) {
  22. return (originalError: any);
  23. }
  24. return new GraphQLError(
  25. originalError.message,
  26. (originalError: any).nodes ?? nodes,
  27. (originalError: any).source,
  28. (originalError: any).positions,
  29. path,
  30. originalError,
  31. );
  32. }