【发布时间】:2017-01-31 23:25:02
【问题描述】:
他们已经是关于这个话题的问题了
Node.js Best Practice Exception Handling
这是旧的,答案非常过时,domains 从那时起甚至已弃用。
现在在后 Async/Await Node.js 场景中,我们不应该类似地考虑同步和异步情况,并在同步函数中抛出异常并在异步函数中拒绝承诺,而不是在前一种情况下返回 Error 实例。
let divideSync = function(x,y) {
// if error condition?
if ( y === 0 ) {
// "throw" the error
throw new Error("Can't divide by zero exception")
}
else {
// no error occured, continue on
return x/y
}
}
模拟异步除法操作
let divideAsync = function(x, y) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
// if error condition?
if (y === 0) {
// "throw" the error safely by rejecting the promise
reject (new Error("Can't divide by zero exception"));
} else {
// no error occured, continue on
resolve(x / y)
}
}, 1000);
})
};
所以同步和异步异常可以统一处理
let main = async function () {
try {
//const resultSync = divideSync(4,0);
const resultAsync = await divideAsync(4,0);
}
catch(ex) {
console.log(ex.message);
}
}
【问题讨论】:
标签: javascript node.js async-await ecmascript-next