Recently, a global filter needs to be added to the service. The filter verifies the input for front-end monitoring. One of the issues to deal with is how to send an exception log after a validation failure. In this process, I learned about the exception handling mechanism of VUE.

ErrorCaptured, errorHandler

Vue provides two apis for catching exceptions, errorCaptured and errorHandler:

  1. errorCaptured

    ErrorCaptured is a component hook function that catches exceptions at the component level. When this hook function returns false, it prevents the exception from bubbling up further, otherwise it will be passed on to the parent component until the root component.

  2. errorHandler

    ErrorHandler is a global configuration item used to catch exceptions globally. ErrorHandler = function (err, VM, info) {}.

error.js

In the vue source code, the exception handling logic is placed in/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 } }Copy the code

The file is not long and exposes a handleError method, which is called where exceptions need to be caught. The handleError method first captures the component that is reporting the error, then recursively searches for the parent of the current component and calls errorCaptured in turn. The globalHandleError method is called when errorCaptured methods have been called, or when errorCaptured methods report errors.

The globalHandleError method calls the global errorHandler method.

What if the errorHandler method itself returns an error? In production, console.error is printed in the console.

ErrorCaptured and errorHandler are both triggered the same way. ErrorCaptured occurs first, and if errorCaptured returns false, The exception message will no longer bubble up and the errorHandler method will not be called.