Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle if error.originalError.errors is not array #1095

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
})
Loading