使用nodejs时,Try/Catch块没有捕获我的错误

问题描述 投票:0回答:1

这是我的职责:

interface MyUserRequest extends Request {
    user?: any;
}

type MyToken = {
    patientId: number
    name: string
  }

const SECRET: Secret = process.env.PATIENT_SECRET!

const patientAuthMiddleware = async (req: MyUserRequest, res: Response, next:NextFunction) => {
    const {token} = req.cookies

    try{

        const {patientId, name} = jwt.verify(token, SECRET) as MyToken
        req.user = {patientId, name}  
        next()
    }
    catch(error){
        throw new UnauthenticatedError('You are not authorized to access this route')
    }
}

好吧,基本上,上面发生的事情是这个函数是一个中间件,我的应用程序有两个用户,一个病人和一个医生。这是上面的耐心中间件,我将其放在路线前面,如下所示:

app.use('/patient', patientAuthMiddleware, patientRouter)

所以当你登录时,中间件会从 cookie 中获取你的 token,并在使用 jwt 验证后获取患者 ID,显然这意味着如果医生登录,患者 ID 就不会存在(医生有自己的 ID)中间件,也有同样的问题),它的目的是捕获该错误并响应“您无权访问此路由”,如上所示。然而,当用邮递员进行测试时,当我尝试以医生的身份访问患者路线时,它会显示以下消息:

"msg": "Cannot destructure property 'name' of '(intermediate value)' as it is null."

这显然意味着患者ID不存在于医生身上,但是,它应该被捕获为错误,并且应该输出正确的响应,另请注意,这个确切的代码之前按预期工作,它用于按预期捕获错误,然而,当我今天早上再次测试它时,它开始这样做,我不确定发生了什么。

node.js typescript jwt try-catch
1个回答
0
投票

您在这里使用

patientAuthMiddleware

app.use('/patient', patientAuthMiddleware, patientRouter)

这是 Express 中间件。它希望您向它传递一个函数,而 Express 根本不查看该函数的返回值。

但是,您将

patientAuthMiddleware
声明为
async
函数。这意味着当您在该函数内执行此操作时:

throw new UnauthenticatedError('You are not authorized to access this route')

async
函数将捕获该异常并将其作为拒绝的承诺返回。但是,Express 根本不考虑返回值。因此,Express 不会检测到您的错误。


不清楚为什么您将该函数声明为

async
,因为通常这样做是为了您可以使用
await
,但您没有显示任何
await
的使用。但是,假设你需要它是
async
,而不是抛出错误,你可以直接调用
next(err)
并告诉你的错误,以确保 Express 知道它,如下所示:

const patientAuthMiddleware = async (req: MyUserRequest, res: Response, next:NextFunction) => {
    const {token} = req.cookies

    try{

        const {patientId, name} = jwt.verify(token, SECRET) as MyToken
        req.user = {patientId, name}  
        next()
    }
    catch(error){
        next(new UnauthenticatedError('You are not authorized to access this route'))
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.