背景
是時候一站式統一處理異常?。。。ㄡ槍ue項目)
全局異常捕獲
Vue.config.errorHandler = function (err, vm, info) { // 指定組件的渲染和觀察期間未捕獲錯誤的處理函數。這個處理函數被調用時,可獲取錯誤信息和 Vue 實例。 // handle error // `info` 是 Vue 特定的錯誤信息,比如錯誤所在的生命周期鉤子 // 只在 2.2.0+ 可用 }
注意:面對異常處理,同步異常和異步異常應該區別對待分別處理。
vue核心源碼剖析
通過閱讀源碼看一下vue是如何將Vue.config.errorHandler接口暴露給使用者。
同步異常處理方案
// 定義異常處理函數,判斷用戶是否自定義Vue.config.errorHandler,定義則直接調用,未定義執行vue本身異常處理。function globalHandleError(err, vm, info) { if (Vue.config.errorHandler) { try { return config.errorHandler.call(null, err, vm, info) } catch (e) { logError(e, null, 'config.errorHandler'); } } logError(err, vm, info);}try { // vue正常執行代碼被包裹在try內,有異常會調用globalHandleError} catch (e) { globalHandleError(e, vm, '對應信息');}
異步異常處理方案
// 定義異步異常處理函數,對于自身沒有捕獲異常的promise統一執行catchfunction invokeWithErrorHandling( handler, context, args, vm, info) { var res; try { res = args ? handler.apply(context, args) : handler.call(context); if (res && !res._isVue && isPromise(res) && !res._handled) { res.catch(function (e) { return handleError(e, vm, info + " (Promise/async)"); }); // 異步代碼例如promise可以統一為其定義Promise.prototype.catch()方法。 res._handled = true; } } catch (e) { handleError(e, vm, info); } return res}// 所有的鉤子函數調用異常處理函數function callHook(vm, hook) { var handlers = vm.$options[hook]; // 為所有鉤子增加異常處理 var info = hook + " hook"; if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { invokeWithErrorHandling(handlers[i], vm, null, vm, info); } }}
知識延伸
// vue接口是能處理同步異常以及部分鉤子中的異步異常,對于方法中的異常無法有效處理,我們可以仿照源碼增加方式中的異步異常處理,避免為每一個promise寫catchVue.mixin({ beforeCreate() { const methods = this.$options.methods || {} Object.keys(methods).forEach(key => { let fn = methods[key] this.$options.methods[key] = function (...args) { let ret = fn.apply(this, args) if (ret && typeof ret.then === 'function' && typeof ret.catch === "function") { return ret.catch(Vue.config.errorHandler) } else { // 默認錯誤處理 return ret } } }) }})
完整代碼
下面是全局處理異常的完整代碼,已經封裝成一個插件
errorPlugin.js/** * 全局異常處理 * @param { * } error * @param {*} vm */const errorHandler = (error, vm, info) => { console.error('拋出全局異常') console.error(vm) console.error(error) console.error(info)}let GlobalError = { install: (Vue, options) => { /** * 全局異常處理 * @param { * } error * @param {*} vm */ Vue.config.errorHandler = errorHandler Vue.mixin({ beforeCreate() { const methods = this.$options.methods || {} Object.keys(methods).forEach(key => { let fn = methods[key] this.$options.methods[key] = function (...args) { let ret = fn.apply(this, args) if (ret && typeof ret.then === 'function' && typeof ret.catch === "function") { return ret.catch(errorHandler) } else { // 默認錯誤處理 return ret } } }) } }) Vue.prototype.$throw = errorHandler }}export default GlobalError
使用
// 在入口文件中引入import ErrorPlugin from './errorPlugin'import Vue from 'vue'Vue.use(ErrorPlugin)
寫在最后
增加全局異常處理有助于
資料參考
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對武林網的支持。
新聞熱點
疑難解答