zoukankan      html  css  js  c++  java
  • 如何让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 库里。里面有更多的短方法供大家使用;

  • 相关阅读:
    移动端
    vue2.0实战记录
    vue学习记录
    JS中数字计算精度
    10亿个字符串的排序问题
    <nginx.conf> nginx用户权限
    详解jquery插件中;(function ( $, window, document, undefined )的作用
    nginx服务器安装及配置文件详解
    移动端HTML5<video>视频播放优化实践
    打造自己的html5视频播放器
  • 原文地址:https://www.cnblogs.com/hrw3c/p/15262717.html
Copyright © 2011-2022 走看看