node.jserror-handlinggoogle-authenticationhapigoogle-auth-library-nodejs

@hapi/boom not returning correct error, instead "500 : Internal Server Error"


@hapi/boom is not returning correct error as thrown in code. Here is the code sample:

controller.ts

async (request: IRequest, h: IResponse) => {
.... // some logic
   const userInfo = await verify(email, authToken)
   if (!userInfo) throw Boom.unauthorized(`Unable to fetch user information`)
.... some logic
   return h.response({ statusCode: 200, message: "Success", data })
} catch (error) {
   throw error
}

verify.ts

export async function verify(userEmail: string, token: string) {
   try {
    const ticket = await client.verifyIdToken({
       idToken: token,
       audience: clientId
    })
    const payload = ticket.getPayload()
    if (!payload) throw Boom.unauthorized("Google authentication failed")
    const { sub: userId, name, email, aud, picture: profilePhoto } = payload
    if (!aud || aud !== clientId) throw Boom.unauthorized(`Invalid token for ${config.get("appName")}`)
    if (!email || email !== userEmail) throw Boom.unauthorized(`Invalid token for email ${userEmail}`)
    return { userId, name, profilePhoto, email }
 } catch (error) {
    logger.error(error)
    throw error
 }
}

Now, on error, it should either return Unauthorized, but it is returning Internal Server Error always.

Any solution to return actual error with information?

stack:

@hapi/hapi : 20.0.3

@hapi/boom : 9.1.1


Solution

  • I guess it won't help you anymore, since the question is 9 months old, but in the code you posted clientId is undefined in the try block. This means you end up in the catch block and (re)throw the original error.

    Since you are using a regular throw in the catch block, hapi calls throw Boom.internal(), which is a HTTP 500 internal server error.