简体   繁体   中英

GraphQL How to seperate Server errors from Client errors (ideally using TryCatch blocks) in node.js?

        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.

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"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM