【问题标题】:How to handle error in Express Passport deserializeUser如何处理 Express Passport 反序列化用户中的错误
【发布时间】:2019-03-16 10:00:42
【问题描述】:

如何将来自 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)

【问题讨论】:

    标签: express authentication mongoose passport.js


    【解决方案1】:

    问题解决了:

    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);
    };
    

    【讨论】:

      猜你喜欢
      • 2013-03-20
      • 2018-07-23
      • 1970-01-01
      • 2018-03-30
      • 2012-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多