How to catch errors gracefully

The previous code logic often appeared:

// 假设这是一个API接口调用
function userInfo () {
    
    
  return new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
      resolve({
    
    
        data: {
    
    
          name: '张三', age: 18
        },
        code: '000'
      })
    }, 3000)
  })
}
// 在页面加载调用这个函数
async function getUserInfo () {
    
    
  try {
    
    
    let res = await userInfo()
    console.log('正常处理...')
  } catch (error) {
    
    
    // 错误捕获
  }
}

Encapsulation error capture

async function useCaptured (asyncFunc) {
    
    
  try {
    
    
    const res = await asyncFunc()
    return [null, res]
  } catch (error) {
    
    
    return [error, null]
  }
}

Then introduce the above helper function in any file you need. The encapsulation rule of this helper function is to follow the error first rule, which is similar to node, and the function name follows the form of hooks.

function userInfo () {
    
    
  return new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
      resolve({
    
    
        data: {
    
    
          name: '张三', age: 18
        },
        code: '000'
      })
    }, 3000)
  })
}

async function getUserInfo () {
    
    
  let [err, res] = await useCaptured(userInfo)
  if (!err) {
    
    
    console.log('正常处理...')
  }
}

Isn't it great! ! !

Reference article

Guess you like

Origin blog.csdn.net/wu_xianqiang/article/details/108133374