异步的异常处理 - pod4g/tool GitHub Wiki

1. 无法用try...catch捕获异步抛出的异常

(function () {
 try {
   setTimeout(() => {
     console.log(111)
     throw new Error('抛出异常 ....') // 这个在异步中抛出的异常并不会被catch住
   })
 } catch (error) {
   console.log('callAsync.catch:', error)
 }
})()

catch不住异步抛出的异常的原因在于:try...catch是同步的,依次往下执行,当抛出异常时,catch早执行完了

2. 在bluebird和原生promise中

const asyncFn = a => {
  return new Promise((resolve, reject) => {
    if (a === 1) {
      throw new Error('a不能等于1')
    }
    setTimeout(() => {
      resolve('success ...')
    }, 1000)
  })
}

asyncFn(1).then(msg => console.log(msg)).catch(e => {
  console.log('catch:', e)
})

在promise中抛出的异常能够被catch函数捕获

3. nodejs的error first回调策略

nodejs的异步回调中的第一个参数是error对象,执行过程中发生的任何异常,都会作为回调函数的第一个参数,所以我们就能在回调中处理异常