Skip to content

Commit 90cfe0e

Browse files
committed
Improved error handling for variables parsing
1 parent 34ebe02 commit 90cfe0e

File tree

1 file changed

+34
-25
lines changed

1 file changed

+34
-25
lines changed

src/components/GraphiQL.js

+34-25
Original file line numberDiff line numberDiff line change
@@ -478,9 +478,14 @@ export class GraphiQL extends React.Component {
478478
let jsonVariables = null;
479479

480480
try {
481-
jsonVariables = JSON.parse(variables);
481+
jsonVariables =
482+
variables && variables.trim() !== '' ? JSON.parse(variables) : null;
482483
} catch (error) {
483-
jsonVariables = null;
484+
throw new Error(`Variables are invalid JSON: ${error.message}.`);
485+
}
486+
487+
if (typeof jsonVariables !== 'object') {
488+
throw new Error('Variables are not a JSON object.');
484489
}
485490

486491
const fetch = fetcher({
@@ -521,10 +526,7 @@ export class GraphiQL extends React.Component {
521526

522527
return subscription;
523528
} else {
524-
this.setState({
525-
isWaitingForResponse: false,
526-
response: 'Fetcher did not return Promise or Observable.'
527-
});
529+
throw new Error('Fetcher did not return Promise or Observable.');
528530
}
529531
}
530532

@@ -549,27 +551,34 @@ export class GraphiQL extends React.Component {
549551
}
550552
}
551553

552-
// _fetchQuery may return a subscription.
553-
const subscription = this._fetchQuery(
554-
editedQuery,
555-
variables,
556-
operationName,
557-
result => {
558-
if (queryID === this._editorQueryID) {
559-
this.setState({
560-
isWaitingForResponse: false,
561-
response: JSON.stringify(result, null, 2),
562-
});
554+
try {
555+
// _fetchQuery may return a subscription.
556+
const subscription = this._fetchQuery(
557+
editedQuery,
558+
variables,
559+
operationName,
560+
result => {
561+
if (queryID === this._editorQueryID) {
562+
this.setState({
563+
isWaitingForResponse: false,
564+
response: JSON.stringify(result, null, 2),
565+
});
566+
}
563567
}
564-
}
565-
);
568+
);
566569

567-
this.setState({
568-
isWaitingForResponse: true,
569-
response: null,
570-
subscription,
571-
operationName,
572-
});
570+
this.setState({
571+
isWaitingForResponse: true,
572+
response: null,
573+
subscription,
574+
operationName,
575+
});
576+
} catch (error) {
577+
this.setState({
578+
isWaitingForResponse: false,
579+
response: error.message
580+
});
581+
}
573582
}
574583

575584
handleStopQuery = () => {

0 commit comments

Comments
 (0)