From 04d9bc3883de9a98f11c327976a82034e8397c82 Mon Sep 17 00:00:00 2001 From: Dan Castillo Date: Mon, 22 Apr 2024 08:57:46 -0400 Subject: [PATCH] fix: handle if error.originalError.errors is not array (#1095) * fix: handle if error.originalError.errors is not array * add tests --- lib/errors.js | 2 +- test/errors.js | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 1 deletion(-) diff --git a/lib/errors.js b/lib/errors.js index e9502e31..34b9516f 100644 --- a/lib/errors.js +++ b/lib/errors.js @@ -44,7 +44,7 @@ function defaultErrorFormatter (execution, ctx) { log.info({ err: error }, error.message) // it handles fastify errors MER_ERR_GQL_VALIDATION - if (error.originalError?.errors) { + if (error.originalError?.errors && Array.isArray(error.originalError.errors)) { // not all errors are `GraphQLError` type, we need to convert them return error.originalError.errors.map(toGraphQLError) } diff --git a/test/errors.js b/test/errors.js index c968adda..818b0c89 100644 --- a/test/errors.js +++ b/test/errors.js @@ -1239,3 +1239,81 @@ test('errors - should default to HTTP Status Code `200 OK` if single error prese }) t.equal(res.statusCode, 200) }) + +test('errors - return GraphQLError when `error.originalError.errors` is of type array', async (t) => { + t.plan(2) + + const schema = ` + type Query { + errors: [String!]! + } + ` + + const app = Fastify() + t.teardown(app.close.bind(app)) + + app.register(GQL, { + schema, + resolvers: { + Query: { + errors () { + throw new ErrorWithProps('Error', undefined, 500) + } + } + } + }) + + await app.ready() + + const res = await app.inject({ + method: 'GET', + url: '/graphql?query={array}' + }) + + t.same(JSON.parse(res.body), { + data: null, + errors: [ + { + message: 'Cannot query field "array" on type "Query".', + locations: [{ line: 1, column: 2 }] + } + ] + }) + t.equal(res.statusCode, 400) +}) + +test('errors - return error when `error.originalError.errors` is not an array or not defined', async (t) => { + t.plan(2) + + const schema = ` + type Query { + errorArray: [String!]! + } + ` + const app = Fastify() + t.teardown(app.close.bind(app)) + + app.register(GQL, { + schema, + resolvers: {} + }) + + await app.ready() + + const res = await app.inject({ + method: 'GET', + url: '/graphql?query={errorArray}' + }) + + t.same(JSON.parse(res.body), { + data: null, + errors: [ + { + message: 'Cannot return null for non-nullable field Query.errorArray.', + locations: [{ line: 1, column: 2 }], + path: ['errorArray'] + } + ] + }) + t.equal(res.statusCode, 200) +})