如何优雅地细粒度管理错误捕获?

如何优雅地细粒度管理错误捕获?

比如我有下面这段代码

async function xxx() {
    const result1 = await getInfo1() 
    
    const result2 = await getInfo2(paramsBasedResult1)
    ... 
}

错误捕获?

async function xxx() {
    try {
        const result1 = await getInfo1() 
        try {
            const result2 = await getInfo2(paramsBasedResult1);
            ....
        }catch(error) {
            ...
        }
    }catch(error) {
        ....
    }
}

一层套一层给我感觉就像是回调地狱。

以我这段代码为例(下面是我做的错误处理的方式,可以将try catch去掉,去实现你自己的错误捕获处理)

async function loadChart() {
  // 1. 获取管理区代码

  // 2. 拼接管理区代码,发送请求

  // 3. 处理数据
  //
  option.xAxis.data = []
  option.series = []
  try {
    const params1 = {
      gs_id: 'xxNnrViL4f',
      p_id: 'xxNnrViL4f'
    };

    const result1 = await getOrgTree(params1);
    if (!result1.isSucceed) throw new Error(result1.errMsg);

    try{
      const mergeGlqdm = result1.data[0].datas.reduce((pre, cur) => pre + "," + cur.code, "").slice(1);
      const params2 = {
        glqdm: mergeGlqdm,
        xmdm: props.xmdm,
        ksrq: props.ksrq,
        jsrq: props.jsrq
      }
      const result2 = await getChartData(params2);
      if (!result2.isSucceed) throw new Error(result2.errMsg);

      const data = result2.data[0].datas;
      let preRq = "9999-99-99";
      let isCollectAllDate = false;
      for (const item of data) {
        if (item.rq > preRq) {
          option.series[option.series.length - 1].data.push(item.zbz);
        } else {
          option.series.push({
            data: [item.zbz],
            type: "line",
            name: `系列${option.series.length + 1}`
          })
          if (preRq !== "9999-99-99") {
            isCollectAllDate = true;
          }
        }
        if (!isCollectAllDate) option.xAxis.data.push(item.rq);
        preRq = item.rq;
      }
      myChart.setOption(option);
    }catch(error) {
      ElMessage.error("获取曲线数据失败,错误信息:" + error.message)
    }
  }catch(error) {
    ElMessage.error("获取分管理区数据失败,错误信息:" + error.message);
  }
}
阅读 1.9k
2 个回答

可以试试这个库:await-to-js

示例:

import to from 'await-to-js';
// If you use CommonJS (i.e NodeJS environment), it should be:
// const to = require('await-to-js').default;

async function asyncTaskWithCb(cb) {
     let err, user, savedTask, notification;

     [ err, user ] = await to(UserModel.findById(1));
     if(!user) return cb('No user found');

     [ err, savedTask ] = await to(TaskModel({userId: user.id, name: 'Demo Task'}));
     if(err) return cb('Error occurred while saving task');

    if(user.notificationsEnabled) {
       [ err ] = await to(NotificationService.sendNotification(user.id, 'Task Created'));
       if(err) return cb('Error while sending notification');
    }

    if(savedTask.assignedUser.id !== user.id) {
       [ err, notification ] = await to(NotificationService.sendNotification(savedTask.assignedUser.id, 'Task was created for you'));
       if(err) return cb('Error while sending notification');
    }

    cb(null, savedTask);
}

async function asyncFunctionWithThrow() {
  const [err, user] = await to(UserModel.findById(1));
  if (!user) throw new Error('User not found');
  
}
async function xxx() {
    const result1 = await getInfo1().catch(e=>{
         console.log(e); 
        return null
    })
    if(!result1) return
    const result2 = await getInfo2(paramsBasedResult1).catch(e=>{ 
        console.log(e);
         return null
    })
    ... 
}
推荐问题
宣传栏