记录Javascript 异常捕获

try...catch

JS中同步过程和ES6中asyn/await函数均可以经过try...catch捕获异常.多层的try/catch能够传递、中断异常。bash

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

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)
});
复制代码

Node.js内部是如何捕获异步错误的ui

相关文章
相关标签/搜索