Skip to content

Commit

Permalink
fix: handle if error.originalError.errors is not array (#1095)
Browse files Browse the repository at this point in the history
* fix: handle if error.originalError.errors is not array

* add tests
  • Loading branch information
dancastillo committed Apr 22, 2024
1 parent e9873db commit 04d9bc3
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
78 changes: 78 additions & 0 deletions test/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})

0 comments on commit 04d9bc3

Please sign in to comment.