• 0
  • 0

uniapp 客户端报错日志收集

2021-05-29 1272 0 admin 所属分类:Hbuilder

进入 main.js 文件 

App.mpType = 'app'

上面代码后添加如下代码

// Vue全局异常捕获  无法处理 异步请求回来的报错 需额外处理
const errorHandler = (error, vm, info) => {
console.error('抛出全局异常');
console.error(vm);
console.error(error);
api.send_js_error(error, vm, info);
};
Vue.config.errorHandler = errorHandler;
Vue.prototype.$throw = (error) => errorHandler(error, this);

在 api 文件 post 请求回调 包裹一层 try catch

if (typeof(res) == 'object') {
    if (callBack != undefined) {
        try{
            callBack(res);
        }catch(e){
            console.log('捕获到 异步回调的异常 ');
            this.send_js_error(e, null, null,url,postData,res)
        }
        
    }
}

send_js_error 实现 ,这样就能同时记录  周期函数报错 和 异步请求返回报错

/*
    处理客户端报错 兼容 生命周期报错  和 服务器请求异步回调报错
    处理方式
    ① 监听生命周期报错 main.js  Vue.config.errorHandler = errorHandler;
    ② URL 请求 回调处添加 try catch 
    @param
        error  异常对象
        vm   vue 报错对象  ② 情况为 null 
        info vue 信息  ② 情况为 null
        url 请求地址  ② 有 ① null 
        post_data 请求地址携带参数 ② 有 ① null
        response_data 请求响应参数 ② 有 ① null
*/
send_js_error(error, vm, info,url,post_data,response_data) {
    if (common.debug == 1) {
        fun.confirm('程序异常, 是否将异常放置到剪辑板?', (confirm) => {
            if (confirm.confirm == true) {
                uni.setClipboardData({
                    data: vm.__route__ + "\n" + error.message + "\n\n" + error.stack
                })
            }
        });
    }
    var msg = "错误类型:" + error.name + "\n";
    if (vm && vm._isVue) {
        msg += "文件路径:" + vm.__route__ + "\n";
        if (vm.$options && vm.$options.__file) {
            msg += "具体路径:" + vm.$options.__file + "\n";
        }
    }
    msg += "错误提示:" + error.message + "\n";
    if (info) {
        msg += "大概位置:" + info + "\n";
    }
    msg += "\n" + error.stack;
    
    if (url) {
        msg += "\n请求的地址:" + url;
        if (url.indexOf('log/errors')!=-1) {
            // 日志记录的报错 过滤
            return false;
        }
    }
    
    if (post_data) {
        msg += "\n请求的参数:" + JSON.stringify(post_data);
    }
    
    if (response_data) {
        msg += "\n响应的参数:" + JSON.stringify(response_data);
    }
    // 具体参数 自行协定  这边是记录 用户的 请求地址 请求参数 返回参数 手机信息等
    var params = {
        'message': msg,
        'client_system':JSON.stringify(common.sysinfo) 
    }
    
    console.log('报错信息:',msg)
    this.post('log', 'errors', params);
}


返回顶部