UNPKG

vue-exception-captor

Version:

用于捕获Vue前端工程中的全局异常、Promise异常,并支持HTTP模式上报到后台存储

1 lines 2.5 kB
!function(){Number.isInteger=Number.isInteger||function(value){return"number"==typeof value&&isFinite(value)&&Math.floor(value)===value};var Axios=require("axios"),VueExceptionCaptor={productName:"unknown",username:"unknown",reportUrl:"",reportClient:null,disabled:!1,console:!1,install:function(Vue,options){this.productName=options.productName||this.productName,this.username=options.username||this.username,this.reportUrl=options.reportUrl||"",this.disabled=options.disabled||!1,this.console=options.console||!1,this.reportClient=Axios.create({baseURL:this.reportUrl,withCredentials:!1,timeout:3e3}),window.onerror=(event,source,lineNo,columnNo,error)=>(this.console&&(console.log("进入了window.onerror"),console.log(error)),this.disabled||this.reportException("window.onerror",error,"捕获全局异常","error"),!0),window.onunhandledrejection=event=>{this.console&&(console.log("进入了window.onunhandledrejection"),console.log(event)),this.disabled||this.reportException("window.onunhandledrejection",event.reason,"捕获全局Promise异常","error")},Vue.config.errorHandler=(error,vm,info)=>{this.console&&(console.log("进入了Vue.config.errorHandler"),console.log(error)),this.disabled||this.reportException("vue.errorHandler",error,"捕获Vue全局异常","error")},Vue.prototype.$exceptionCaptor=this,Vue.prototype.$reportException=this.reportException},async reportException(type,error,message,level="error"){try{const exception=this.getException(type,error,message,level);await this.report(exception)}catch(error){console.log("处理上报的异常出错"),console.log(error)}},getException(type,error,message,level="error"){const jsonError=this.serializeError(error);return{product:this.productName,username:this.username,href:window.location.href,type:type,level:level,message:message||"",error:jsonError}},serializeError(error){try{return error?JSON.stringify(error,Object.getOwnPropertyNames(error),null):""}catch(error){return""}},async report(exception){try{const exceptionStr=JSON.stringify(exception);await this.reportClient({method:"post",data:exceptionStr,headers:{"Content-Type":"application/json"}})}catch(error){console.log("上报全局异常出错"),console.log(error)}},setExceptionUserName(username){this.username=username}};"object"==typeof exports?module.exports=VueExceptionCaptor:"function"==typeof define&&define.amd?define([],(function(){return VueExceptionCaptor})):window.Vue&&(window.VueExceptionCaptor=VueExceptionCaptor,Vue.use(VueExceptionCaptor))}();