How to use the GraphQLError function from graphql

Find comprehensive JavaScript graphql.GraphQLError code examples handpicked from public code repositorys.

graphql.GraphQLError represents an error that occurs during the execution of a GraphQL operation.

37
38
39
40
41
42
43
44
45
46
// Identify validation errors so that customFormatErrorFn will allow them to be returned to the user.
const validationErrors = validate(...args)

return validationErrors.map(
  (error) =>
    new GraphQLError(
      error.message,
      error.nodes,
      error.source,
      error.positions,
fork icon33
star icon66
watch icon0

+ 13 other calls in file

151
152
153
154
155
156
157
158
159
160
return new Promise(function(resolve, reject) {
    mysql.query(`${ mobSchema.selectSQL.mobSelectSQL } ${mobSchema.selectSQL.mobSelectTables} WHERE M.Id = ?`,
        [mobId],
        function(error, results, fields) {
            if (error) {
                reject(new graphql.GraphQLError(error.sqlMessage));
                return;
            }

            if (results.length > 0)
fork icon3
star icon6
watch icon0

+ 20 other calls in file

How does graphql.GraphQLError work?

graphql.GraphQLError is a class in the GraphQL.js library that represents an error that occurs during the execution of a GraphQL operation. When an error occurs, an instance of the GraphQLError class is created and passed along with the result of the GraphQL operation. The instance contains information about the error, such as the error message, the location of the error in the source code, and any relevant path and extension fields. The GraphQLError class also provides methods for creating new instances of the class with modified properties, such as adding or removing locations or modifying the error message. Overall, GraphQLError plays an important role in handling errors that occur during the execution of a GraphQL operation, providing detailed information about the error to aid in debugging and resolving the issue.

83
84
85
86
87
88
89
90
91
92
const Genes = await _gene_model.Gene.find(filter).sort({ 'gene.name': 1 }).limit(limit).skip(offset);
const total = await _controller_common_functions.commonController.countDocumentsIn(_gene_model.Gene, filter);
const lastPage = Math.floor(total / limit);
if (limit * (page + 1) < total) hasMore = true;
if (page > lastPage) {
  const err = new _graphql.GraphQLError('You must select an available page number');
  err.status = 'No Content';
  err.statusCode = 204;
  throw err;
} else {
fork icon1
star icon0
watch icon1

+ 88 other calls in file

168
169
170
171
172
173
174
175
176
177
                });
                return [3 /*break*/, 6];
            case 5:
                error_2 = _a.sent();
                console.error(error_2);
                throw new graphql_1.GraphQLError("Error creating message", error_2 || undefined);
            case 6: return [2 /*return*/, Promise.resolve(true)];
        }
    });
}); },
fork icon0
star icon2
watch icon2

+ 587 other calls in file

Ai Example

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
const { graphql, buildSchema, GraphQLError } = require("graphql");

// Define a schema
const schema = buildSchema(`
type Query {
hello(name: String): String
}
`);

// Define a resolver
const rootValue = {
  hello: ({ name }) => {
    if (name === "foo") {
      throw new GraphQLError('Name cannot be "foo"');
    }
    return `Hello, ${name || "World"}!`;
  },
};

// Execute a query
graphql(schema, '{ hello(name: "foo") }', rootValue)
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.error(error);
  });

In this example, we define a schema and a resolver for a hello query. We intentionally throw a GraphQLError if the name argument is set to "foo". When we execute a query that triggers this error, we catch the error and log it to the console. The error message will be "Name cannot be "foo"".

13
14
15
16
17
18
19
20
21
22
  __dirname,
  `../data/projects/carts/${cartId}.json`
);

const cartExists = await fileExists(cartFilePath);
if (!cartExists) return new GraphQLError("That project does not exist");

const cartData = await fsPromises.readFile(cartFilePath, {
  encoding: "utf-8",
});
fork icon0
star icon0
watch icon1

+ 5 other calls in file

1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
    if (Array.isArray(error)) {
        error[0].extensions.code = error[0].code;
        return new graphql_1.GraphQLError(error[0].message, undefined, undefined, undefined, undefined, error[0]);
    }
    error.extensions.code = error.code;
    return new graphql_1.GraphQLError(error.message, undefined, undefined, undefined, undefined, error);
}
/**
 * Select the correct service for the given collection. This allows the individual services to run
 * their custom checks (f.e. it allows UsersService to prevent updating TFA secret from outside)
fork icon0
star icon0
watch icon1

+ 85 other calls in file

99
100
101
102
103
104
105
106
107
108
toggleLikeComment: async (_, { idUser, idComment }) => {
  console.log("resolver: toggleLikeComment");
  try {
    const comment = await CommentModel.findById(idComment);
    if (!comment) {
      return new GraphQLError("There is no comment with id " + idComment, {
        extensions: { code: "NOT-FOUND" },
      });
    }
    let commentUpdated = undefined;
fork icon0
star icon0
watch icon1

+ 175 other calls in file

52
53
54
55
56
57
58
59
60
61
62
      endpointUrl: data.endpointUrl
    };
    await Resource.create(arrayOfData);
    return await Resource.find({ tenantName: data.tenantName });
  } else {
    throw new GraphQLError(data.name + 'already exist on this Tenant');
  }
}


async function updateResource(data) {
fork icon0
star icon0
watch icon1

+ 33 other calls in file

141
142
143
144
145
146
147
148
149
150
      comments: undefined,
      nbrComments: post.comments.length,
    };
  } catch (errorUpdatePost) {
    console.log("Something went wrong during Update Post", errorUpdatePost);
    return new GraphQLError("Something went wrong during Update Post", {
      extensions: { code: "ERROR-SERVER" },
    });
  }
},
fork icon0
star icon0
watch icon1

+ 1036 other calls in file

50
51
52
53
54
55
56
57
58
59

// Validate data 
const {errors, valid} = validateRegisterInput(name, username, email, role, password, confirmPassword)

if(!valid) {
    throw new GraphQLError('Errors', {
        extensions: {
            code: 'BAD_USER_INPUT',
            errors
        }
fork icon0
star icon0
watch icon1

+ 154 other calls in file

371
372
373
374
375
376
377
378
379
380
      message: "Succesfully added upvoted answer, answer data updated",
      user: _user,
      answer: correspondingAnswer,
    };
  } else {
    throw new GraphQLError("No such user!", {
      extensions: { userId: userId },
    });
  }
},
fork icon0
star icon0
watch icon1

+ 413 other calls in file

4
5
6
7
8
9
10
11
12
13
Object.defineProperty(exports, "__esModule", { value: true });
const graphql_1 = require("graphql");
const vitest_1 = require("vitest");
const process_error_1 = __importDefault(require("./process-error"));
(0, vitest_1.describe)('GraphQL processError util', () => {
    const sampleError = new graphql_1.GraphQLError('An error message', { path: ['test_collection'] });
    const redactedError = {
        message: 'An unexpected error occurred.',
        locations: undefined,
        extensions: {
fork icon0
star icon0
watch icon1

+ 6 other calls in file

36
37
38
39
40
41
42
43
44
45
},
Mutation: {
  addBook: async (root, args, context) => {
    const currentUser = context.currentUser
    if (!currentUser) {
      throw new GraphQLError('not authenticated', {
        extensions: {
          code: 'BAD_USER_INPUT',
        }
      })
fork icon0
star icon0
watch icon1

+ 5 other calls in file