如何讓async await錯誤處理更優雅,如何優雅的做好async await的異常捕獲


我們在使用async await時如果要處理錯誤,如果有多個異步操作,需要每一次書寫 try...catch。這樣代碼的簡潔性較差,且業務代碼需要包含在try...catch中。沒辦法把業務錯誤和代碼錯誤分開;

const fn = async ()=>{
  try{
     //請求如果出錯,會拋出異常
      const res = await  Axios.get('xxxx');

     //如果請求正常,業務代碼錯誤,如下面代碼修改了常量的代碼錯誤也會拋出異常;
     const num;
     num = res.user.num + 1;

  }catch(e){
        //異常處理過於雜亂,違反了單一原則。
        alert(e)
  }  


//多個同步業務處理,代碼不簡潔
  try{
     const res1 = await Axios.get('x1');
     console.log(res1);
  }catch(e){alert(e)}

  try{
       
     const res2 = await Axios.get('x2');
     console.log(res2);

  }catch(e){alert(e)}
}  

 

在工作中還時常看到有小伙伴用法比較奇葩,把async await跟then catch一起用;

//獲取人員數據
        const getStudentStatistics = async ()=>{
            await Axios.get('xxxxxurl').then(res => {
                res = res || {};
                this.studentStatistics = res;
            }).catch(error => {
                this.$alert(error);
            })
        }

這是我實際工作中發現組內小伙伴些的代碼,主要可能還是沒完全理解async await導致的;

 

為了讓代碼更整潔,不出現用法混亂的情況;我在網上找到了有一個小哥的處理還不錯:https://zhuanlan.zhihu.com/p/85865426

借鑒了他的方法,稍微做了修改,更加實用:

/**
 * @param {*} promise 異步方法主體
 * @param {*} fromatResult 是否處理成統一格式,不處理則直接返回第一個參數。 true處理,false不處理,默認為true :::
 * @return {error,resutl}  有錯誤 resutl為null,error為錯誤體。沒錯誤 error為null result為結果
 */
const toAsyncAwait = (promise, fromatResult = true) => {
    if (!fromatResult) {
        return promise;
    } else {
        return promise.then((res) => ({ error: null, result: res })).catch((err) => ({ error: err, result: null }));
    }
}

const fn = async () => {
    // 業務1 使用error判斷
    const { error, result } = await toAsyncAwait(Axios.get('xxx1'));
    if (error) {
        alert(error);
    } else {
        console.log(result);
    }
    // 業務2 使用result判斷  使用這種判斷的時候注意你的返回結果是不是有為null的時候
    const { error: er, result: res } = await toAsyncAwait(Axios.get('xxx1'));
    if (res) {
        console.log(res);
    } else {
        alert(er);
    }
    // 業務三不管錯誤
    const { result: r } = await toAsyncAwait(Axios.get('xxx3'));
    if (r) {
        console.log(r);
    }
}


此方法也加入了平時自己用的 jsutil 庫里。里面有更多的短方法供大家使用;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM