问题描述
我有一个有效的 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,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)
似乎我的成功处理程序和错误处理程序都被调用了,但我不确定我哪里出错了。
解决方法
考虑将请求包装在 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)
}
}