Vue:errorHandler和warnHandler

发布于 2022-04-26  1303 次阅读


这两个函数是错误处理和警告处理的处理器。是全局的,可以全局配置作为拦截器。

app.config#

Every application instance exposes a config object that contains the configuration settings for that application. You can modify its properties (documented below) before mounting your application.

import { createApp } from 'vue'

const app = createApp(/* ... */)

console.log(app.config)

app.config.errorHandler#

Assign a global handler for uncaught errors propagating from within the application.

  • Type
interface AppConfig {
  errorHandler?: (
    err: unknown,
    instance: ComponentPublicInstance | null,
    // `info` is a Vue-specific error info,
    // e.g. which lifecycle hook the error was thrown in
    info: string
  ) => void
}
  • DetailsThe error handler receives three arguments: the error, the component instance that triggered the error, and an information string specifying the error source type.It can capture errors from the following sources:
    • Component renders
    • Event handlers
    • Lifecycle hooks
    • setup() function
    • Watchers
    • Custom directive hooks
    • Transition hooks
  • Example
app.config.errorHandler = (err, instance, info) => {
  // handle error, e.g. report to a service
}

app.config.warnHandler#

Assign a custom handler for runtime warnings from Vue.

  • Type
interface AppConfig {
  warnHandler?: (
    msg: string,
    instance: ComponentPublicInstance | null,
    trace: string
  ) => void
}
  • DetailsThe warning handler receives the warning message as the first argument, the source component instance as the second argument, and a component trace string as the third.It can be used to filter out specific warnings to reduce console verbosity. All Vue warnings should be addressed during development, so this is only recommended during debug sessions to focus on specific warnings among many, and should be removed once the debugging is done.TIPWarnings only work during development, so this config is ignored in production mode.
  • Example
app.config.warnHandler = (msg, instance, trace) => {
  // `trace` is the component hierarchy trace

}

欢迎欢迎~热烈欢迎~