Home > database >  How To Throw Errors In Apollo Server v4?
How To Throw Errors In Apollo Server v4?

Time:10-29

thanks for looking into this. So I am trying to migrate my Apollo Server from V3 to V4, I have a resolver that type checks for an Access Token and returns it like so

export class LoginResolver {
    @Mutation(() => AccessToken)
    async login(
        @Arg("email") email: string,
        @Arg("password") password: string,
        @Ctx() { prisma, res }: ProjectContext
    ): Promise<AccessToken> {
        // check if user exists
        const user = await prisma.user.findFirst({
            where: {
                email,
            },
        });
        if (!user) {
            throw new GraphQLError("No user found");
        }
        const valid = await verify(user.password, password);
        if (!valid) {
            throw new GraphQLError("Invalid Password");
        }
        // the user logged in successully
        res.cookie("*****", createRefreshToken(user), { httpOnly: true });
        const accessToken = createAccessToken(user);
        return {
            accessToken,
        };
    }
}

It returns the following error if the validation fails.

{
  "data": {},
  "error": {
    "message": "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
  }
}

But however, if the right credentials were provided the API works just fine returning me a access token

{
  "data": {
    "login": {
      "accessToken": "..."
    }
  }
}

Correct Input: email : [email protected] password : password

Initially in Apollo V3 I had standard throw statements that worked just fine

        const user = await prisma.user.findFirst({
            where: {
                email,
            },
        });
        if (!user) {
            throw new Error("No user found");
        }
        const valid = await verify(user.password, password);
        if (!valid) {
            throw new Error("Invalid Password");
        }

digging into Apollo server's docs I found that in V4 Apollo Error was removed and GraphQLError from graphql took it's place, I gave that a shot but that does not seem to fix it.

Error Message from the console :

Unexpected error processing request: TypeError: graphqlError.toJSON is not a function
TypeError: graphqlError.toJSON is not a function
    at enrichError (D:\Projects\PlacementHub\backend\node_modules\@apollo\server\src\errorNormalize.ts:84:30)
    at D:\Projects\PlacementHub\backend\node_modules\@apollo\server\src\errorNormalize.ts:46:18
    at Array.map (<anonymous>)
    at normalizeAndFormatErrors (D:\Projects\PlacementHub\backend\node_modules\@apollo\server\src\errorNormalize.ts:39:29)
    at ApolloServer.errorResponse (D:\Projects\PlacementHub\backend\node_modules\@apollo\server\src\ApolloServer.ts:1028:73)
    at ApolloServer.executeHTTPGraphQLRequest (D:\Projects\PlacementHub\backend\node_modules\@apollo\server\src\ApolloServer.ts:1020:19)

CodePudding user response:

I suspect that GraphQLError has a mandatory 2nd argument and Apollo isn't handling it well if it's omitted.

try

throw new GraphQLError('"No user found', {
  extensions: {
    code: 'UNKNOWN_USER',
  },
});

CodePudding user response:

You should use ApolloError for this.


import { ApolloError } from 'apollo-server-express';

throw new ApolloError("there is a big problem");

I did the one for Express in the above line of code. You can download other packages according to your project.

  • Related