最近需要在业务中加一个全局的 filter,filter 会对输入进行验证,用于进行前端监控。其中一个要处理的问题,就是验证失败后如何发送异常日志,这个过程中顺便了解了一下 vue 的异常处理机制。errorCaptured、errorHandlererrorCaptured、errorHandlervue 提供了两个 API 用于异常的捕获,分别是 errorCaptured 和 errorHandler:errorCaptured errorHandler

errorCaptured
errorCapturederrorCaptured 是组件的一个钩子函数,用于在组件级别捕获异常。当这个钩子函数返回 false 时,会阻止异常进一步向上冒泡,否则会不断向父组件传递,直到 root 组件。

errorHandler
errorHandlererrorHandler 是一个全局的配置项,用来在全局捕获异常。例如Vue.config.errorHandler = function (err, vm, info) {}。error.jserror.js在 vue 源码中,异常处理的逻辑放在 /src/core/util/error.js 中:
import config from '../config'
import { warn } from './debug'
import { inBrowser } from './env'

export function handleError (err: Error, vm: any, info: string) {
if (vm) {

let cur = vm

while ((cur = cur.$parent)) {

const hooks = cur.$options.errorCaptured

if (hooks) {

for (let i = 0; i < hooks.length; i++) {

try {

const capture = hooks[i].call(cur, err, vm, info) === false

if (capture) return

} catch (e) {

globalHandleError(e, cur, 'errorCaptured hook')

}

}

}

}
}
globalHandleError(err, vm, info)
}

function globalHandleError (err, vm, info) {
if (config.errorHandler) {

try {

return config.errorHandler.call(null, err, vm, info)

} catch (e) {

logError(e, null, 'config.errorHandler')

}
}
logError(err, vm, info)
}

function logError (err, vm, info) {
if (process.env.NODE_ENV !== 'production') {

warn(`Error in ${info}: "${err.toString()}"`, vm)
}
/* istanbul ignore else */
if (inBrowser && typeof console !== 'undefined') {

console.error(err)
} else {

throw err
}
}
import config from '../config'
import { warn } from './debug'
import { inBrowser } from './env'

export function handleError (err: Error, vm: any, info: string) {
if (vm) {

let cur = vm

while ((cur = cur.$parent)) {

const hooks = cur.$options.errorCaptured

if (hooks) {

for (let i = 0; i < hooks.length; i++) {

try {

const capture = hooks[i].call(cur, err, vm, info) === false

if (capture) return

} catch (e) {

globalHandleError(e, cur, 'errorCaptured hook')

}

}

}

}
}
globalHandleError(err, vm, info)
}

function globalHandleError (err, vm, info) {
if (config.errorHandler) {

try {

return config.errorHandler.call(null, err, vm, info)

} catch (e) {

logError(e, null, 'config.errorHandler')

}
}
logError(err, vm, info)
}

function logError (err, vm, info) {
if (process.env.NODE_ENV !== 'production') {

warn(`Error in ${info}: "${err.toString()}"`, vm)
}
/* istanbul ignore else */
if (inBrowser && typeof console !== 'undefined') {

console.error(err)
} else {

throw err
}
}文件不长,向外暴露了一个 handleError 方法,在需要捕获异常的地方调用。handleError 方法中首先获取到报错的组件,之后递归查找当前组件的父组件,依次调用 errorCaptured 方法。在遍历调用完所有 errorCaptured 方法、或 errorCaptured 方法有报错时,会调用 globalHandleError 方法。globalHandleError 方法调用了全局的 errorHandler 方法。如果 errorHandler 方法自己又报错了呢?生产环境下会使用 console.error 在控制台中输出。可以看到 errorCaptured 和 errorHandler 的触发时机都是相同的,不同的是 errorCaptured 发生在前,且如果某个组件的 errorCaptured 方法返回了 false,那么这个异常信息不会再向上冒泡也不会再调用 errorHandler 方法。以上就是详解Vue 的异常处理机制的详细内容,关于vue 异常处理的资料请关注其它相关文章!