ts(js) 异常包装器 目的: 敏捷开发、减少代码量

355 阅读1分钟

初衷:每次去写请求接口的时候各种toast的状态需要手动维护,写一个包装器去自动清理。

简单封装了一下 try catch 暂时使用没出现问题。 有什么好的建议欢迎评论区留言。

核心代码

// @/utils/hooks/exception.ts

import { Toast } from "vant";

/**
 * 异常包装器
 * @param func 函数
 * @param opts 配置
 * @author maybe
 * @example  
 *   const getData = useCatch(async () => {
      const result = await api.getData();
      state.result = result.data;
    }, {
      toast:true, // 默认是true
      errCallback(err) {
        // console.log( err)
      }
    })
 * @returns 
 */
export const useCatch = (func: Function, opts?: {
    /**
     * 是否开启错误信息toast
     */
    toast?: boolean,
    /**
     * 是否开启加载中
     */
    loading?: boolean,
    /**
     * 错误回调
     */
    errCallback?: (err: any) => void
}) => {
    // 合并配置
    const optsNew = Object.assign({ toast: true, loading: false }, opts)

    return async function () {
        try {
            optsNew.loading && Toast.loading({
                forbidClick: true,
                duration: 0
            });
            await func();
            Toast.clear();
        } catch (error: any) {
            console.error(error);
            // 清除toast
            Toast.clear();
            // 默认弹出错误toast(如果有loading会自动清除loading)
            optsNew.toast && Toast.fail(error.message);
            // 自定义错误回调
            optsNew.errCallback && optsNew.errCallback(error)
            // 继续往上层抛出错误
            throw new Error(error)
        }
    };
}

使用

<script lang="ts" setup>
import { useCatch } from "@/utils/hooks/exception";
import * as api from '@/api/xxx'

const getData = useCatch(async () => {
      const result = await api.getData();
      console.log(result.data);
    });
 onMounted(()=> {
    getData()
 })
</script>