在复杂的前端应用中,错误监控和异常处理是保障用户体验的重要环节。本文将介绍如何建立完善的前端错误监控体系。
1 JavaScript运行时错误捕获
// 全局错误捕获window.addEventListener('error',(event)=>{console.error('全局错误:',event.error)// 上报错误信息reportError({message:event.error.message,filename:event.filename,lineno:event.lineno,colno:event.colno,stack:event.error.stack})})// Promise未捕获异常window.addEventListener('unhandledrejection',(event)=>{console.error('未处理的Promise异常:',event.reason)// 阻止默认行为event.preventDefault()reportError({message:event.reason.message||event.reason,type:'unhandledrejection',stack:event.reason.stack})})2 Vue组件错误处理
// Vue全局错误处理app.config.errorHandler=(err,instance,info)=>{console.error('Vue错误:',err)reportError({message:err.message,component:instance?.$options.name,info,stack:err.stack})}// 组件级错误处理exportdefault{errorCaptured(err,instance,info){// 处理子组件错误console.error('组件错误:',err)returnfalse// 阻止错误继续传播}}3 错误上报与分析
// 错误上报服务classErrorReporter{constructor(options){this.endpoint=options.endpointthis.batchSize=options.batchSize||10this.errors=[]}report(error){this.errors.push({...error,timestamp:Date.now(),userAgent:navigator.userAgent,url:location.href})if(this.errors.length>=this.batchSize){this.sendBatch()}}sendBatch(){if(this.errors.length===0)returnfetch(this.endpoint,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(this.errors)}).catch(err=>{console.error('错误上报失败:',err)})this.errors=[]}}