不要给 async 函数写那么多 try/catch 了

  • 在开发中,你是否会为了系统健壮性,亦或者是为了捕获异步的错误,而频繁的在 async 函数中写 try/catch 的逻辑?
async function func() {
    try {
        let res = await asyncFunc()
    } catch (e) {
      //......
    }
}
  • 处理 async/await 的方法
async function errorCaptured(asyncFunc) {
    try {
        const res = await asyncFunc()
        return [null, res]
    } catch (e) {
        return [e, null]
    }
}
  • 这样我们就可以使用一个辅助函数包裹这个 async 函数实现错误捕获
async function func() {
    const [err, res] = await errorCaptured(asyncFunc)

    if (err) {
        // 错误处理
    }
}

但是这么做有一个缺陷就是每次使用的时候,都要引入 errorCaptured 这个辅助函数,有没有“懒”的方法呢? 答案肯定是有的,我在那篇博客后提出了一个新的思路,可以通过一个 webpack loader 来自动注入 try/catch 代码,最后的结果希望是这样的

推荐错误处理babel插件open in new window

贡献者: mankueng