如何讓async await錯誤處理更優雅
阿新 • • 發佈:2021-09-13
我們在使用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 庫裡。裡面有更多的短方法供大家使用;