一种实现简单且舒服的前端接口异常处理方案

11次阅读

共计 914 个字符,预计需要花费 3 分钟才能阅读完成。

业务逻辑中,在处理接口数据的时候,除了要处理正常情况,也要处理异常情况。

处理方案多种多样,在这里介绍一个我常用的方案,在该方案中,业务代码只需处理数据正常的情况,无需处理:数据异常、接口请求报错(try catch)等。

以 Vue 项目为例。

该方案的开发体验

业务代码中的写法:

export default {async created() {const res = await this.getData();
        
        if (res !== null) {// 处理正常逻辑}
        
        // 如果 res 是 null,则不做任何处理
        // 隐藏的统一处理逻辑会负责错误提示等
    },
    
    methods: {getData() {
            return this.$ajax({// 各类参数})
        }
    }
}

效果:

  • 业务代码中只需要处理 res 不为 null 的情况,只要 res !== null (true)

    只要数据返回有值,只处理该情况即可。

  • 隐藏的统一处理逻辑会负责错误提示、返回数据格式化等

如何实现

实现方案也很简单。大家可以看到上面代码中用到了 this.$ajax

在 Vue 中就是新增一个 $ajax 插件即可。代码如下:

  • ajaxPlugin.js

    let $ajax = axios.create({// ... 各类配置});
        
    let $newAjax = (config) => {
        const $vm = this;
        
        return $ajax(config)
            .then(res => {
                // 这里统一处理异常情况
                // 同时也可以将数据返回值格式统一化
                
                if (res.code !== 200) {$vm.$message.error(res.message);
                    return null;
                } else {
                    return {data: res.data};
                }
            }).catch(err => {$vm.$message.error(err);
                return null;
            });
    };
    
    export default {install(){Vue.prototype.$ajax = $newAjax;}
    };
  • index.js

    import ajaxPlugin from './ajaxPlugin';
    Vue.use(ajaxPlugin);

总结

我在多个项目中实现了这套处理逻辑,在实际的开发体验中,感觉非常不错。

在这里分享给大家。

正文完
 0