Best practice to return ApolloErrors from Nexus resolver

Viewed 321

I'm currently struggeling with returning errors from my resolvers created with nexus and typescript.
I know that nexus isn't supposed to handle errors but we still have to define a return type for the mutation/query and that makes it impossible to just return a new ApolloError because nexus does not allow to return either the success value (like a user object) or an error.

export const confirmEmail = mutationField('confirmEmail', {
  type: Boolean | ApolloError, // not allowed by nexus
  args: {
    email: nonNull(stringArg()),
    code: nonNull(stringArg()),
  },
  resolve: async (_, args, ctx) => {
    const user = await ctx.prisma.user.findUnique({
      where: {
        email: args.email,
      },
    })

    if (!user) {
      return new ApolloError('User does not exists', 'BAD_USER_INPUT')
    }
    await sendEmail(
      'jonashiltl2003@gmail.com',
      `<p>Your confirmation code is: </p> <b>${args.code}</b>`,
      'Confirmation Code',
    )
    return true
  },
})

Just to mention, it does work to just define one type for a mutation/query and still return an ApolloError but Typescript complains because then in some cases the ApolloError gets returned and not the defined one.

Is there a cleaner way to return errors from resolvers and stay typesafe?

0 Answers
Related