From 9569200b95e86a2e0074e9e54153dbfb98a62602 Mon Sep 17 00:00:00 2001 From: SachaG <358832+SachaG@users.noreply.github.com> Date: Tue, 7 Aug 2018 15:43:03 +0900 Subject: [PATCH] Improve error handling by parsing GraphQL error messages --- packages/vulcan-lib/lib/modules/errors.js | 56 ++++++++++++++++++++++- 1 file changed, 54 insertions(+), 2 deletions(-) diff --git a/packages/vulcan-lib/lib/modules/errors.js b/packages/vulcan-lib/lib/modules/errors.js index 7656004b9..b70de26c0 100644 --- a/packages/vulcan-lib/lib/modules/errors.js +++ b/packages/vulcan-lib/lib/modules/errors.js @@ -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;