File size: 1,906 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
70
71
72
73
74
// @flow
const debug = require('debug')('api:utils:error-formatter');
import Raven from 'shared/raven';
import { IsUserError } from './UserError';
import type { GraphQLError } from 'graphql';

const queryRe = /\s*(query|mutation)[^{]*/;

const collectQueries = query => {
  if (!query) return 'No query';
  return query
    .split('\n')
    .map(line => {
      const m = line.match(queryRe);
      return m ? m[0].trim() : '';
    })
    .filter(line => !!line)
    .join('\n');
};

const errorPath = error => {
  if (!error.path) return '';
  return error.path
    .map((value, index) => {
      if (!index) return value;
      return typeof value === 'number' ? `[${value}]` : `.${value}`;
    })
    .join('');
};

const logGraphQLError = (req, error) => {
  debug('---GraphQL Error---');
  debug(error);
  error &&
    error.extensions &&
    error.extensions.exception &&
    debug(error.extensions.exception.stacktrace.join('\n'));
  if (req) {
    debug(collectQueries(req.body.query));
    debug('variables', JSON.stringify(req.body.variables || {}));
  }
  const path = errorPath(error);
  path && debug('path', path);
  debug('-------------------\n');
};

const createGraphQLErrorFormatter = (req?: express$Request) => (
  error: GraphQLError
) => {
  logGraphQLError(req, error);

  const err = error.originalError || error;
  const isUserError = err[IsUserError];

  let sentryId = 'ID only generated in production';
  if (!isUserError) {
    if (process.env.NODE_ENV === 'production') {
      sentryId = Raven.captureException(
        error,
        req && Raven.parsers.parseRequest(req)
      );
    }
  }

  return {
    message: isUserError ? error.message : `Internal server error: ${sentryId}`,
    // Hide the stack trace in production mode
    stack:
      !process.env.NODE_ENV === 'production' ? error.stack.split('\n') : null,
  };
};

export default createGraphQLErrorFormatter;