errorNormalize.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { GraphQLError, } from 'graphql';
  2. import { ApolloServerErrorCode } from './errors/index.js';
  3. import { mergeHTTPGraphQLHead, newHTTPGraphQLHead } from './runHttpQuery.js';
  4. import { HeaderMap } from './utils/HeaderMap.js';
  5. export function normalizeAndFormatErrors(errors, options = {}) {
  6. const formatError = options.formatError ?? ((error) => error);
  7. const httpFromErrors = newHTTPGraphQLHead();
  8. return {
  9. httpFromErrors,
  10. formattedErrors: errors.map((error) => {
  11. try {
  12. return formatError(enrichError(error), error);
  13. }
  14. catch (formattingError) {
  15. if (options.includeStacktraceInErrorResponses) {
  16. return enrichError(formattingError);
  17. }
  18. else {
  19. return {
  20. message: 'Internal server error',
  21. extensions: { code: ApolloServerErrorCode.INTERNAL_SERVER_ERROR },
  22. };
  23. }
  24. }
  25. }),
  26. };
  27. function enrichError(maybeError) {
  28. const graphqlError = ensureGraphQLError(maybeError);
  29. const extensions = {
  30. ...graphqlError.extensions,
  31. code: graphqlError.extensions.code ??
  32. ApolloServerErrorCode.INTERNAL_SERVER_ERROR,
  33. };
  34. if (isPartialHTTPGraphQLHead(extensions.http)) {
  35. mergeHTTPGraphQLHead(httpFromErrors, {
  36. headers: new HeaderMap(),
  37. ...extensions.http,
  38. });
  39. delete extensions.http;
  40. }
  41. if (options.includeStacktraceInErrorResponses) {
  42. extensions.stacktrace = graphqlError.stack?.split('\n');
  43. }
  44. return { ...graphqlError.toJSON(), extensions };
  45. }
  46. }
  47. export function ensureError(maybeError) {
  48. return maybeError instanceof Error
  49. ? maybeError
  50. : new GraphQLError('Unexpected error value: ' + String(maybeError));
  51. }
  52. export function ensureGraphQLError(maybeError, messagePrefixIfNotGraphQLError = '') {
  53. const error = ensureError(maybeError);
  54. return error instanceof GraphQLError
  55. ? error
  56. : new GraphQLError(messagePrefixIfNotGraphQLError + error.message, {
  57. originalError: error,
  58. });
  59. }
  60. function isPartialHTTPGraphQLHead(x) {
  61. return (!!x &&
  62. typeof x === 'object' &&
  63. (!('status' in x) || typeof x.status === 'number') &&
  64. (!('headers' in x) || x.headers instanceof Map));
  65. }
  66. //# sourceMappingURL=errorNormalize.js.map