SoFunction
Updated on 2025-04-05

Elegant practical records for handling exceptions of vue projects

background

  • Are you still worried about dealing with Uncaught (in promise) ReferenceError?
  • Are you still writing try catch repeatedly to catch exceptions?
  • Are you still writing catch for every promise?

It's time to handle exceptions in one-stop unified way! ! ! (For vue projects)

Global exception capture

 = function (err, vm, info) {
 // Specifies a handler function that does not catch errors during rendering and observation of the component.  When this handler is called, error information and Vue instances can be obtained. 
 // handle error
 // `info` is a Vue specific error message, such as the life cycle hook where the error is located // Only available in 2.2.0+}

Notice:In the face of exception handling, synchronous exceptions and asynchronous exceptions should be treated separately.

Analysis of vue core source code

Read the source code to see how vue exposes the interface to the user.

Synchronous exception handling scheme

// Define the exception handling function to determine whether the user is customizing it. If the definition is called directly, the exception handling of vue itself is not defined.function globalHandleError(err, vm, info) {
 if () {
  try {
   return (null, err, vm, info)
  } catch (e) {
   logError(e, null, '');
  }
 }
 logError(err, vm, info);
}
try {
 // Vue's normal code execution is wrapped in a try. If there is an exception, globalHandleError will be called.} catch (e) {
 globalHandleError(e, vm, 'Complied Information');
}

Asynchronous exception handling scheme

// Define an asynchronous exception handling function and execute catch for promises that do not catch exceptions.function invokeWithErrorHandling(
 handler,
 context,
 args,
 vm,
 info
) {
 var res;
 try {
  res = args ? (context, args) : (context);
  if (res && !res._isVue && isPromise(res) && !res._handled) {
   (function (e) { return handleError(e, vm, info + " (Promise/async)"); });
   // Asynchronous code such as promise can uniformly define the() method for it.   res._handled = true;
  }
 } catch (e) {
  handleError(e, vm, info);
 }
 return res
}

// All hook functions call exception handling functionsfunction callHook(vm, hook) {
 var handlers = vm.$options[hook];
 // Add exception handling to all hooks var info = hook + " hook";
 if (handlers) {
  for (var i = 0, j = ; i < j; i++) {
   invokeWithErrorHandling(handlers[i], vm, null, vm, info);
  }
 }
}

Extension of knowledge

// The vue interface can handle synchronous exceptions and asynchronous exceptions in some hooks. For exceptions in the method cannot be effectively handled, we can simulate the asynchronous exception handling in the source code addition method to avoid writing catch for each promise({
 beforeCreate() {
  const methods = this.$ || {}
  (methods).forEach(key => {
   let fn = methods[key]
   this.$[key] = function (...args) {
    let ret = (this, args)
    if (ret && typeof  === 'function' && typeof  === "function") {
     return ()
    } else { // Default error handling     return ret
    }
   }
  })
 }
})

Complete code

Below is the complete code for global exception handling, which has been encapsulated into a plug-in


/**
  * Global exception handling
  * @param {
  * } error
  * @param {*} vm
  */
const errorHandler = (error, vm, info) => {
 ('Top global exception')
 (vm)
 (error)
 (info)
}
let GlobalError = {
 install: (Vue, options) => {
 /**
   * Global exception handling
   * @param {
   * } error
   * @param {*} vm
   */
   = errorHandler
  ({
   beforeCreate() {
    const methods = this.$ || {}
    (methods).forEach(key => {
     let fn = methods[key]
     this.$[key] = function (...args) {
      let ret = (this, args)
      if (ret && typeof  === 'function' && typeof  === "function") {
       return (errorHandler)
      } else { // Default error handling       return ret
      }
     }
    })
   }
  })
  .$throw = errorHandler
 }
}
export default GlobalError

use

//Introduce in the entry fileimport ErrorPlugin from './errorPlugin'
import Vue from 'vue'
(ErrorPlugin)

Written at the end

Adding global exception handling helps

  • Improve code robustness
  • Reduce crashes
  • Quickly locate bugs

Data reference

  • /vuejs/vue/b…
  • /v2/api/#err…

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support.