mirror of
https://github.com/vale981/Vulcan
synced 2025-03-06 10:01:40 -05:00
Improve error handling by parsing GraphQL error messages
This commit is contained in:
parent
d9784ad0aa
commit
9569200b95
1 changed files with 54 additions and 2 deletions
|
@ -1,5 +1,57 @@
|
|||
/*
|
||||
|
||||
Get whatever word is contained between the first two double quotes
|
||||
|
||||
*/
|
||||
const getFirstWord = input => {
|
||||
const parts = /"([^"]*)"/.exec(input);
|
||||
if (parts === null) {
|
||||
return null;
|
||||
}
|
||||
return parts[1];
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
Parse a GraphQL error message
|
||||
|
||||
Sample message:
|
||||
|
||||
"GraphQL error: Variable "$data" got invalid value {"meetingDate":"2018-08-07T06:05:51.704Z"}.
|
||||
In field "name": Expected "String!", found null.
|
||||
In field "stage": Expected "String!", found null.
|
||||
In field "addresses": Expected "[JSON]!", found null."
|
||||
|
||||
*/
|
||||
|
||||
const parseErrorMessage = message => {
|
||||
|
||||
// note: optionally add .slice(1) at the end to get rid of the first error, which is not that helpful
|
||||
let fieldErrors = message.split('\n');
|
||||
|
||||
fieldErrors = fieldErrors.map(error => {
|
||||
// field name is whatever is between the first to double quotes
|
||||
const fieldName = getFirstWord(error);
|
||||
if (error.includes('found null')) {
|
||||
// missing field errors
|
||||
return {
|
||||
id: 'errors.required',
|
||||
path: fieldName,
|
||||
properties: {
|
||||
name: fieldName,
|
||||
},
|
||||
}
|
||||
} else {
|
||||
// other generic GraphQL errors
|
||||
return {
|
||||
message: error
|
||||
}
|
||||
}
|
||||
});
|
||||
return fieldErrors;
|
||||
}
|
||||
/*
|
||||
|
||||
Errors can have the following properties stored on their `data` property:
|
||||
- id: used as an internationalization key, for example `errors.required`
|
||||
- path: for field-specific errors inside forms, the path of the field with the issue
|
||||
|
@ -33,8 +85,8 @@ export const getErrors = error => {
|
|||
errors = [graphQLError.data];
|
||||
}
|
||||
} else {
|
||||
// 4. there is no data object, just use raw error
|
||||
errors = [graphQLError];
|
||||
// 4. there is no data object, try to parse raw error message
|
||||
errors = parseErrorMessage(graphQLError.message);
|
||||
}
|
||||
}
|
||||
return errors;
|
||||
|
|
Loading…
Add table
Reference in a new issue