Skip to content

Commit 04d9bc3

Browse files
authored
fix: handle if error.originalError.errors is not array (#1095)
* fix: handle if error.originalError.errors is not array * add tests
1 parent e9873db commit 04d9bc3

File tree

2 files changed

+79
-1
lines changed

2 files changed

+79
-1
lines changed

lib/errors.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ function defaultErrorFormatter (execution, ctx) {
4444
log.info({ err: error }, error.message)
4545

4646
// it handles fastify errors MER_ERR_GQL_VALIDATION
47-
if (error.originalError?.errors) {
47+
if (error.originalError?.errors && Array.isArray(error.originalError.errors)) {
4848
// not all errors are `GraphQLError` type, we need to convert them
4949
return error.originalError.errors.map(toGraphQLError)
5050
}

test/errors.js

+78
Original file line numberDiff line numberDiff line change
@@ -1239,3 +1239,81 @@ test('errors - should default to HTTP Status Code `200 OK` if single error prese
12391239
})
12401240
t.equal(res.statusCode, 200)
12411241
})
1242+
1243+
test('errors - return GraphQLError when `error.originalError.errors` is of type array', async (t) => {
1244+
t.plan(2)
1245+
1246+
const schema = `
1247+
type Query {
1248+
errors: [String!]!
1249+
}
1250+
`
1251+
1252+
const app = Fastify()
1253+
t.teardown(app.close.bind(app))
1254+
1255+
app.register(GQL, {
1256+
schema,
1257+
resolvers: {
1258+
Query: {
1259+
errors () {
1260+
throw new ErrorWithProps('Error', undefined, 500)
1261+
}
1262+
}
1263+
}
1264+
})
1265+
1266+
await app.ready()
1267+
1268+
const res = await app.inject({
1269+
method: 'GET',
1270+
url: '/graphql?query={array}'
1271+
})
1272+
1273+
t.same(JSON.parse(res.body), {
1274+
data: null,
1275+
errors: [
1276+
{
1277+
message: 'Cannot query field "array" on type "Query".',
1278+
locations: [{ line: 1, column: 2 }]
1279+
}
1280+
]
1281+
})
1282+
t.equal(res.statusCode, 400)
1283+
})
1284+
1285+
test('errors - return error when `error.originalError.errors` is not an array or not defined', async (t) => {
1286+
t.plan(2)
1287+
1288+
const schema = `
1289+
type Query {
1290+
errorArray: [String!]!
1291+
}
1292+
`
1293+
const app = Fastify()
1294+
t.teardown(app.close.bind(app))
1295+
1296+
app.register(GQL, {
1297+
schema,
1298+
resolvers: {}
1299+
})
1300+
1301+
await app.ready()
1302+
1303+
const res = await app.inject({
1304+
method: 'GET',
1305+
url: '/graphql?query={errorArray}'
1306+
})
1307+
1308+
t.same(JSON.parse(res.body), {
1309+
data: null,
1310+
errors: [
1311+
{
1312+
message: 'Cannot return null for non-nullable field Query.errorArray.',
1313+
locations: [{ line: 1, column: 2 }],
1314+
path: ['errorArray']
1315+
}
1316+
]
1317+
})
1318+
t.equal(res.statusCode, 200)
1319+
})

0 commit comments

Comments
 (0)