1
        try {
            const res = await UserModel.findOne({username: username})
            if (res === null) {
                throw new Error("Your username or password was incorrect USERNAME")
            }
            const passwordValid = await bcrypt.compare(password, res.hash);
            if (!passwordValid) {
                throw new Error("Your username or password was incorrect PASSWORD")
            } else {
                console.log("res is: ", res)
                const convertBalanceToNum = {
                    ...res._doc,
                    balance: res.balance.toString()
                }
                console.log("converted balance is: ", convertBalanceToNum)
                return convertBalanceToNum
            }
        } catch (error) {
            console.error(error)
            throw new Error("Unable to verify password due to server error")
        }

I wouldn like to seperate client errors, such as a client supplying the wrong username or password combination, from server errors that does not involve the client giving the wrong info.

Ideally the throw new Error statements inside the Try block would be for client errors, and the one inside the Catch block would be for server errors.

But when the wrong username or password combination get's triggered, the catch block triggers instead of the error statements inside the try block

That would make sense, but now I'm left confused as to how I can implement server specific errors in GraphQL, Any help?

EDIT: I am aware that I could assign the error argument in the catch statement to the throw new Error instead of that string, but I am afraid it might give out sensitive information in cases I haven't accounted for.

momomo
  • 319
  • 1
  • 5
  • 15
  • Throw special errors (such as `new UserError`) and then forward these in your `catch` block – Bergi Jul 29 '21 at 09:12
  • How can I forward that special error to my catch block? Would they be in the same scope? – momomo Jul 29 '21 at 11:32
  • I meant to re-throw it. Just `if (error instanceof UserError) throw error; else throw new Error("Internal server error");` – Bergi Jul 29 '21 at 11:53

1 Answers1

-1

I'm rather a bit new to GraphQL myself, I figured out a makeshift solution, add 2 fields to the UserType, one is called statusCode of GraphQLInt type, the other is serverMessage of GraphQLString type, then return data this way:

{
   ...payload
   statusCode: 401,
   serverMessage: "Could Not Verify Due To Some Error"
}
momomo
  • 319
  • 1
  • 5
  • 15
  • you could try maybe classifying the type of exception thrown by the try, catch block. here is an example: https://stackoverflow.com/a/1433608/6393618 – rya Jul 29 '21 at 07:29