formatError.js.flow 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // @flow strict
  2. import devAssert from '../jsutils/devAssert';
  3. import { type SourceLocation } from '../language/location';
  4. import { type GraphQLError } from './GraphQLError';
  5. /**
  6. * Given a GraphQLError, format it according to the rules described by the
  7. * Response Format, Errors section of the GraphQL Specification.
  8. */
  9. export function formatError(error: GraphQLError): GraphQLFormattedError {
  10. devAssert(error, 'Received null or undefined error.');
  11. const message = error.message || 'An unknown error occurred.';
  12. const locations = error.locations;
  13. const path = error.path;
  14. const extensions = error.extensions;
  15. return extensions
  16. ? { message, locations, path, extensions }
  17. : { message, locations, path };
  18. }
  19. /**
  20. * @see https://github.com/graphql/graphql-spec/blob/master/spec/Section%207%20--%20Response.md#errors
  21. */
  22. export type GraphQLFormattedError = {|
  23. /**
  24. * A short, human-readable summary of the problem that **SHOULD NOT** change
  25. * from occurrence to occurrence of the problem, except for purposes of
  26. * localization.
  27. */
  28. +message: string,
  29. /**
  30. * If an error can be associated to a particular point in the requested
  31. * GraphQL document, it should contain a list of locations.
  32. */
  33. +locations: $ReadOnlyArray<SourceLocation> | void,
  34. /**
  35. * If an error can be associated to a particular field in the GraphQL result,
  36. * it _must_ contain an entry with the key `path` that details the path of
  37. * the response field which experienced the error. This allows clients to
  38. * identify whether a null result is intentional or caused by a runtime error.
  39. */
  40. +path: $ReadOnlyArray<string | number> | void,
  41. /**
  42. * Reserved for implementors to extend the protocol however they see fit,
  43. * and hence there are no additional restrictions on its contents.
  44. */
  45. +extensions?: { [key: string]: mixed, ... },
  46. |};