try...catch
JS中同步过程和ES6中asyn/await函数都可以通过try...catch捕获异常.多层的try/catch可以传递、中断异常。
try {
return x/y;
} catch(e) {
console.error(e);
}
复制代码
try {
try {
...
throw Error("error");
} catch(e) {
console.error("inner");
} finally {
console.error("Final");
}
} catch(e) {
console.error("outer")
}
// ============ console out
// inner
// Final
// outer
复制代码
在finally中显示的return可以中断error的传播。参考MSDN try...catch
Promise中的异常处理
Promise异常无法通过try/catch捕获,而是通过Promise.catch进行处理。
async function() {
try {
await quey();
} catch(e) {
console.log(e);
}
}
复制代码
Promise.resolve().then((resolve, reject) => {
throw Error("Error");
}).catch((e) => {console.log(e});
复制代码
问题
Promise使用时不一定会记得处理异常,导致Promise一直处于pending的状态。NodeJS提供了一个事件来监听是否原生的Promise进行了异常处理
process.on('unhandledRejection', function (err, p) {
console.error('catch exception:',err.stack)
});
复制代码