傳統的前端監控原理分爲異常捕獲和異常上報。通常使用onerror
捕獲前端錯誤:javascript
window.onerror = (msg, url, line, col, error) => { console.log('onerror') // TODO }
可是onerror
事件沒法捕獲到網絡異常的錯誤(資源加載失敗、圖片顯示異常等),例如img
標籤下圖片url 404 網絡請求異常的時候,onerror
沒法捕獲到異常,此時須要監聽unhandledrejection
。前端
window.addEventListener('unhandledrejection', function(err) { console.log(err) })
捕獲的異常如何上報?經常使用的發送形式主要有兩種:vue
function report(error) { var reportUrl = 'http://xxxx/report' new Image().src = reportUrl + '?error=' + error }
sentry是一套開源的強大的前端異常監控上報工具,官網地址:https://sentry.io,官方提供瞭如何搭建sentry服務,此處略過安裝流程,直接使用已有的服務。java
針對vue,sentry官方推薦使用raven配合sentry進行異常捕獲和上報。而在vue中,vue提供了錯誤捕獲方法vue error handler
,官方也推薦使用錯誤追蹤服務 sentry 並經過vue error handler
選項提供了官方支持。jquery
raven是sentry官方針對vue推薦的插件,yarn安裝raven-js便可。ajax
$ yarn add raven-js
初始化引入Vue、Raven、RavenVue便可,sentry能主動監聽上報錯誤。promise
import Raven from 'raven-js' import RavenVue from 'raven-js/plugins/vue' const dsn = 'https://<key1>@sentry.io/<key2>' Raven.config(dsn).addPlugin(RavenVue, Vue).install()
對於一些其餘信息,如提示日誌等,沒法自動捕獲,須要手動進行上報。網絡
log (data = null, type = 'error', options = {}) { // 添加麪包屑 Raven.captureBreadcrumb({ message: data, category: 'manual message' }) // 異常上報 if (data instanceof Error) { Raven.captureException(data, { level: type, logger: 'manual exception', tags: { options: options } }) } else { Raven.captureException('error', { level: type, logger: 'manual data', extra: { data: data, options: this.options, date: new Date() } }) } }
針對上述內容,封裝異常上報類Report,使用單例模式,避免監控類重複實例化。工具
/**
* by csxiaoyao
* 2019.03.17
* sunjianfeng@csxiaoyao.com
*/
import Raven from 'raven-js' import RavenVue from 'raven-js/plugins/vue' class Report { static dsn = 'https://<key1>@sentry.io/<key2>' constructor (Vue, options = {}) { if (process.env.NODE_ENV === 'production') { // TODO } this.Vue = Vue this.options = options } /** * 單例模式 */ static getInstance (Vue, options) { if (!(this.instance instanceof this)) { this.instance = new this(Vue, options) this.instance.install() this.instance.registerError() } return this.instance } /** * init */ install () { Raven.config(Report.dsn, { release: '1.0.0', environment: 'production' // whitelistUrls: [/localhost/, /test\.oa\.com/] }).addPlugin(RavenVue, this.Vue).install() // 記錄用戶信息 Raven.setUserContext({ user: this.options.user || '' }) // 設置全局tag標籤 Raven.setTagsContext({ environment: this.options.env || '' }) } /** * 註冊全局錯誤處理 */ registerError () { // 監聽error window.onerror = (msg, url, line, col, error) => { console.log('onerror') if (msg !== 'Script error.' && !url) { return true } setTimeout(() => { let data = {} col = col || (window.event && window.event.errorCharacter) || 0 data.url = url data.line = line data.col = col data.error = error if (&& error.stack) { data.msg = error.stack.toString() } this.log(data) }, 0) return true } // 監聽promise window.addEventListener('unhandledrejection', err => { console.log('unhandledrejection') setTimeout(() => { this.log(JSON.stringify