我对 Promise 的理解并不完美。
所以我不确定哪种代码是处理错误和异常情况的正确方法。
请帮助我正确编写代码。
第一。 try - catch Sequelize 的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是否可以捕获sequelizer的promise.catch()。
第二。不处理sequelizer的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
也是 Promise 函数。
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);
}
});
});
}
最佳答案
如果您的函数返回 Promise,则无需使用“async”,因为 async
函数返回 Promise
。
我的意思是, var somethink = wait doSomethink()
的结果不是一个 promise ,它是一个对象,因为你从一个 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
。
如果jwtAuth
或doGetAdminList
抛出错误.catch
将收到错误。
如果在 doGetAdminList
中,您没有对 sequelize.query
执行 .catch
,那么 sequelize 错误
将传至你的捕获
就在这里。但是如果你想处理错误并重新抛出错误是可能的。
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/await
执行 getAdminList
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);
}
};
关于node.js - 将promise.reject处理为try-catch或promise.catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47716263/