护照本地猫鼬:未处理的承诺拒绝警告:未处理的承诺拒绝

时间:2021-02-22 15:11:44

标签: express async-await passport.js passport-local-mongoose

我有一个有效的 pasport-local-mongoose 实现,但我正在尝试转向 async/await,并且出现错误。

这是我的控制器:

module.exports.register = async (req, res, next) => {

    const user = new User(),
        fillable = [
            'title',
            'firstName',
            'lastName',
            'practice',
            'addressLine1',
            'addressLine2',
            'city',
            'state',
            'postcode',
            'jobTitle',
            'country',
            'locale',
            'userRole',
            'termsAccepted',
            'consentOptIn',
            'username',
            'password',
            'legacyUserId',
            'authType'
        ]

    populateModel(user, fillable, req.body) // this is just a helper to set the schema from the request

    const result = await User.register(user, req.body.password).catch(next)

    return responseHelper.handleSuccess(res, {
        user: result
    })

}

我在一个辅助模块中有两个响应处理程序:

module.exports.handleSuccess = (res, data) => {

  return res.json({
    message: 'Success.',
    data: data
  })

}

module.exports.handleUnexpectedError = (res, err) => {

  return res.status(err.status || 500).json({
    message: err.message || 'Internal Server Error.',
    error: err
  })

}

我的应用有一个错误处理程序作为中间件:

app.use((err, req, res, next) => responseHelper.handleUnexpectedError(res, err))

最后是调用控制器方法的路由器:

router.post('/auth/register', authController.register)

成功响应没问题,当在这一行抛出错误并传递给中间件时,它确实按预期返回:

const result = await User.register(user, req.body.password).catch(next)

但是,当抛出该错误时,我在控制台中收到一个错误:

POST /v1/auth/register 500 166 - 9.253 ms
(node:21488) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:518:11)
    at ServerResponse.header (/Users/russback/Sites/api.alignpatientexperience.co.uk/node_modules/express/lib/response.js:771:10)
    at ServerResponse.send (/Users/russback/Sites/api.alignpatientexperience.co.uk/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/Users/russback/Sites/api.alignpatientexperience.co.uk/node_modules/express/lib/response.js:267:15)
    at Object.module.exports.handleSuccess (/Users/russback/Sites/api.alignpatientexperience.co.uk/helpers/responseHelper.js:95:14)
    at module.exports.register (/Users/russback/Sites/api.alignpatientexperience.co.uk/controllers/authController.js:64:27)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:21488) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

似乎我的成功处理程序和错误处理程序都被调用了,但我不确定我哪里出错了。

1 个答案:

答案 0 :(得分:0)

考虑将请求包装在 try/catch 块中并在 catch 块内调用 next 回调。

module.exports.register = async (req, res, next) => {

   const user = new User(),
       fillable = [
              ...
       ]

   populateModel(user, fillable, req.body) // this is just a helper to set the schema from the request

   try {
     const result = await User.register(user, req.body.password)

     return responseHelper.handleSuccess(res, {
       user: result
     })

   } catch(error) {
     next(error)
   }

}