errorNormalize.js 2.8 KB

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