首页 文章

处理promise.reject到try-catch或promise.catch

提问于
浏览
1

我对承诺的理解并不完美 .
所以我不确定哪种代码是处理错误和异常情况的正确方法 .

请求帮助我正确编写代码 .

1 . 尝试 - grab 续集器的promise.reject

async function doGetAdminList(adminName) {

      let adminList;
      try {
        adminList = await sequelize.query(
          sqls.GET_ADMIN_LIST,
          { replacements: { adminName: adminName }, type: sequelize.QueryTypes.SELECT }
        );
      } catch (e) {
        return Promise.reject({status:500, message: "SQL Error" });
      }    

      if (!adminList || !Object.keys(adminList).length) {
        log.info('\nadminList not found :\n');
        return Promise.reject({status:400, message: 'adminList not found.' })
      } 

      return adminList;
    }

为此,我想知道try-catch是否可以捕获续集器的promise.catch() .

第2位 . 不要处理续集器的promise.reject

async function doGetAdminList(adminName) {
          let adminList;
          adminList = await sequelize.query(
              sqls.GET_ADMIN_LIST,
              { replacements: { adminName: adminName }, type: sequelize.QueryTypes.SELECT }
          );

          if (!adminList || !Object.keys(adminList).length) {
            log.info('\nadminList not found :\n');
            return Promise.reject({status:400, message: 'adminList not found.' })
          } 

          return adminList;
        }

为此,我想知道sequelizer的promise.reject()是否可以传递调用函数并在promise.catch()中捕获调用者 .

上面的sequelize-using函数将在下面的express函数中使用 .

adminController.js

const jwtAuth = require('../common/jwtAuth.js');

exports.getAdminList = function (req, res) {
  res.setHeader("Content-Type", "application/json; charset=utf-8");

  if (!req.body.adminName) {
    return res.status(400).json({ message: 'adminName is empty.' });
  }

  jwtAuth(req.headers.accesstoken)
  .then((decoded) => {
    worker = decoded.loginName;
    return doGetAdminList(adminName);
  })
  .then((adminList) => {
    log.info("getAdminList() finish");
    res.status(200).json(adminList);
  })
  .catch(e => {
    log.error(e);
    return res.status(e.status).json(e);
  });
};

jwtAuth.js 也是承诺功能 .

const jwt = require('jsonwebtoken');
module.exports = async function verifyJwt(token) {
  return await new Promise((resolve, reject) => {
    if (!token) {
      reject({status:401, message:'Empty token'});
      return;
    }

    jwt.verify(token,"dipa",function(err, decoded){
      if(err) {
        reject({status:401, message:'TokenExpiredError'});
      } else {
        resolve(decoded);
      }
    });
  }); 
}

1 回答

  • 0

    如果函数返回一个promise,则无需使用'async',因为 async 函数返回 Promise .

    我的意思是 var somethink = await doSomethink() 的结果不是它的一个对象的承诺,因为你从 async 函数返回它,它返回为 Promise.resolve(somethink ) .

    所以你的'jwtAuth.js'没有更好

    const jwt = require('jsonwebtoken');
    module.exports = function verifyJwt(token) {
      return new Promise((resolve, reject) => {
        if (!token) {
          reject({status:401, message:'Empty token'});
          return;
        }
    
        jwt.verify(token,"dipa",function(err, decoded){
          if(err) {
            reject({status:401, message:'TokenExpiredError'});
          } else {
            resolve(decoded);
          }
        });
      }); 
    }
    

    同样如此

    function doGetAdminList(adminName) {
    
      let adminList;
    
      return sequelize.query(
        sqls.GET_ADMIN_LIST, {
          replacements: {
            adminName: adminName
          },
          type: sequelize.QueryTypes.SELECT
        }
      ).catch((e)=> {
        //here you catch you sequelize error which can be anything
        //you can either catch and throw a new Error
        log.info('\nadminList not found :\n');
        throw Error({
          status: 500,
          message: "SQL Error"
        })
      })
    
    }
    

    关于 getAdminList 和最后的 catch .

    如果 jwtAuthdoGetAdminList 抛出错误 .catch 将收到错误 .

    如果在 doGetAdminList 中你没有在 sequelize.query 上做 .catch 那么 sequelize error 将在这里前往你的 catch . 但是,如果您想处理错误并重新抛出,则可能出现错误 .

    const jwtAuth = require('../common/jwtAuth.js');
    
    exports.getAdminList = function (req, res) {
      res.setHeader("Content-Type", "application/json; charset=utf-8");
    
      if (!req.body.adminName) {
        res.status(400).json({ message: 'adminName is empty.' });
      }
    
      jwtAuth(req.headers.accesstoken)
      .then((decoded) => {
        worker = decoded.loginName;
        return doGetAdminList(adminName);
      })
      .then((adminList) => {
        log.info("getAdminList() finish");
        res.status(200).json(adminList);
      })
      .catch(e => {
        //the message with mess "SQL Error" will travel here.
        log.error(e);
        res.status(e.status).json(e);
      });
    };
    

    添加,如果你不想改变错误,但你想记录和传递错误,你可以重新抛出它

    .catch(function(e) {
        log.info('\nadminList not found :\n');
        throw e;
      })
    

    如果你想用 async/awaitgetAdminList

    exports.getAdminList = async function(req, res) {
      res.setHeader("Content-Type", "application/json; charset=utf-8");
    
      if (!req.body.adminName)
        res.status(400).json({message: 'adminName is empty.'});
    
      try {
    
        let decoded = await jwtAuth(req.headers.accesstoken)
        worker = decoded.loginName;
    
        let adminList = await doGetAdminList(req.body.adminName);
        log.info("getAdminList() finish");
    
        res.status(200).json(adminList);
    
      } catch (e) {
         //the message with mess "SQL Error" will travel here.
        log.error(e);
        res.status(e.status).json(e);
      }
    
    };
    

相关问题