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

add ErrorWithProps handler for mercurius hook #700

Merged
merged 3 commits into from
Jan 6, 2022
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 @@ -43,7 +43,7 @@ function toGraphQLError (err) {
}

function defaultErrorFormatter (err, ctx) {
let errors = [{ message: err.message }]
let errors = [err instanceof ErrorWithProps ? formatError(toGraphQLError(err)) : { message: err.message }]
// There is always app if there is a context
const log = ctx.reply ? ctx.reply.log : ctx.app.log

Expand Down
48 changes: 48 additions & 0 deletions test/hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const { mapSchema } = require('@graphql-tools/utils')
const { parse, buildSchema, GraphQLSchema } = require('graphql')
const { promisify } = require('util')
const GQL = require('..')
const { ErrorWithProps } = GQL

const immediate = promisify(setImmediate)

Expand Down Expand Up @@ -281,6 +282,53 @@ test('preParsing hooks should handle errors', async t => {
})
})

test('preParsing hooks should handle ErrorWithProps', async t => {
t.plan(4)
const app = await createTestServer(t)

app.graphql.addHook('preParsing', async (schema, source, context) => {
t.type(schema, GraphQLSchema)
t.equal(source, query)
t.type(context, 'object')
throw new ErrorWithProps('a preParsing error occured', { code: 'USER_ID_INVALID' })
})

app.graphql.addHook('preParsing', async (schema, source, context) => {
t.fail('this should not be called')
})

app.graphql.addHook('preValidation', async (schema, document, context) => {
t.fail('this should not be called')
})

app.graphql.addHook('preExecution', async (schema, document, context) => {
t.fail('this should not be called')
})

app.graphql.addHook('onResolution', async (execution, context) => {
t.fail('this should not be called')
})

const res = await app.inject({
method: 'POST',
headers: { 'content-type': 'application/json' },
url: '/graphql',
body: JSON.stringify({ query })
})

t.same(JSON.parse(res.body), {
data: null,
errors: [
{
message: 'a preParsing error occured',
extensions: {
code: 'USER_ID_INVALID'
}
}
]
})
})

test('preParsing hooks should be able to put values onto the context', async t => {
t.plan(8)
const app = await createTestServer(t)
Expand Down