如何将错误从passport.deserializeUser传递给我的错误处理中间件,然后运行req.logout注销用户?
passport.deserializeUser((id, done) => {
Family.findById(id).then(family => {
done(null, family);
});
});
[0] (node:28528) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "abc123" at path "_id" for model "families"
[0] at new CastError (/xxxx/server/node_modules/mongoose/lib/error/cast.js:29:11)
[0] at ObjectId.cast (/xxxx/server/node_modules/mongoose/lib/schema/objectid.js:158:13)
[0] at ObjectId.SchemaType.applySetters (/xxxx/server/node_modules/mongoose/lib/schematype.js:724:12)
[0] at ObjectId.SchemaType._castForQuery (/xxxx/server/node_modules/mongoose/lib/schematype.js:1113:15)
[0] at ObjectId.SchemaType.castForQuery (//xxxx/node_modules/mongoose/lib/schematype.js:1103:15)
[0] at ObjectId.SchemaType.castForQueryWrapper (/xxxx/server/node_modules/mongoose/lib/schematype.js:1082:15)
[0] at cast (/xxxx/server/node_modules/mongoose/lib/cast.js:303:32)
[0] at model.Query.Query.cast (/xxxx/server/node_modules/mongoose/lib/query.js:3524:12)
[0] at model.Query.Query._castConditions (/xxxx/server/node_modules/mongoose/lib/query.js:1392:10)
[0] at model.Query.Query._findOne (/xxxx/server/node_modules/mongoose/lib/query.js:1624:8)
[0] at process.nextTick (/xxxx/server/node_modules/kareem/index.js:333:33)
[0] at process._tickCallback (internal/process/next_tick.js:150:11)
答案 0 :(得分:0)
问题已解决:
在deserializeUser
中捕获Mongoose错误,并将错误发送给中间件:
passport.deserializeUser((id, done) => {
Family.findById(id)
.then(family => {
done(null, family);
})
.catch(error => {
done(error);
});
});
通过index.js
的最后几行处理错误处理中间件中的错误:
[...]
app.use(require('./middlewares/errorHandler_Final'));
app.listen(5000);
定义自定义错误中间件:errorHandler_Final.js
module.exports = (err, req, res, next) => {
if (res.headersSent) {
console.log('HEADERS ALREADY SENT');
return next(err);
}
if (err.name === 'CastError') {
// specifically handles that error. In my case,
// if session id gets corrupted, delete the cookie from client browser.
// req.logout alone was not enough.
// NB the cookie had been created by cookie-session
req.session = null;
req.logout;
return res.sendStatus(500);
}
return res.sendStatus(err.status || 500);
};