如何故意做出承诺失败?有时我只是跳过测试并假设一切都很好,但我想故意让失败的承诺,以便我的捕获工作。
exports.submitJob = async (req, res, next) => {
const { cv } = req.body
const userId = req.user._id
try {
if(!cv) {
//how to pass error to catch block?
}
const save_submission = new Submission({
userId,
cv
}).save()
} catch(e => {
res.json({
status: 0,
error: e
})
})
next()
}
答案 0 :(得分:0)
使用throw语句,也许?
if(!cv) {throw("cv is absent");}
用户定义的异常类型(类似于Java或PHP中通常也有它们)也是可能的并且是推荐的,因为一个字符串几乎不能区分类型,否则可以很容易地检查typeof
中的异常catch
块。刚刚从MDN那里学到了,例如。也可以抛出DOMException和Error。
答案 1 :(得分:0)
您可以throw new Error('<your string here>');
:
请注意,catch
不能与function
语法一起使用 - 正确的语法是catch (e) { /* block that uses e */ }
const submitJobWhichWillFail = async (req, res, next) => {
const cv = null;
try {
if (!cv) {
throw new Error('cv must not be falsey!');
}
const save_submission = new Submission({
userId,
cv
}).save()
} catch (e) {
console.log('res.json with error ' + e);
}
}
submitJobWhichWillFail();
&#13;