diff --git a/__tests__/lib/autotracking.exception.spec.js b/__tests__/lib/autotracking.exception.spec.js new file mode 100644 index 0000000..891f577 --- /dev/null +++ b/__tests__/lib/autotracking.exception.spec.js @@ -0,0 +1,37 @@ +import Vue from 'vue' +import VueAnalytics from '../../src' + +window.ga = jest.fn() + +const originalErrorHandler = jest.fn() +Vue.config.errorHandler = originalErrorHandler + +Vue.use(VueAnalytics, { + id: 'UA-1234-5', + autoTracking: { + exception: true, + }, +}) + +const renderError = new Error('render error') +let $vm + +beforeEach(() => { + $vm = new Vue({ + created() { + throw renderError + } + }) + $vm.$mount() +}) + +it('should track Vue render error', () => { + expect(window.ga).toBeCalledWith('send', 'exception', { + exDescription: 'render error', + exFatal: true + }) +}) + +it('should preserve original error handler', () => { + expect(originalErrorHandler).toBeCalledWith(renderError, $vm, 'created hook') +}) diff --git a/src/index.js b/src/index.js index a4326d9..266173a 100644 --- a/src/index.js +++ b/src/index.js @@ -7,7 +7,7 @@ import ga from 'directives/ga' // Features import event from 'lib/event' -import exception from 'lib/exception' +import exception, { setupErrorHandler } from 'lib/exception' import page from 'lib/page' import query from 'lib/query' import require from 'lib/require' @@ -36,6 +36,8 @@ export default function install (Vue, options = {}) { commands: config.commands } + setupErrorHandler(Vue) + bootstrap() } diff --git a/src/lib/exception.js b/src/lib/exception.js index f579e11..2303971 100644 --- a/src/lib/exception.js +++ b/src/lib/exception.js @@ -8,6 +8,18 @@ export default function exception (error, fatal = false) { }) } +export function setupErrorHandler(Vue) { + if (config.autoTracking.exception) { + const originalErrorHandler = Vue.config.errorHandler + Vue.config.errorHandler = function (error, vm, info) { + vm.$ga.exception(error.message || error, true) + if (typeof originalErrorHandler === 'function') { + originalErrorHandler.call(this, error, vm, info) + } + } + } +} + export function autotracking () { if (!config.autoTracking.exception) { return