Skip to content

[vue] 怎么捕获组件vue的错误信息? #327

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

[vue] 怎么捕获组件vue的错误信息?

Activity

Sihan-Tan

Sihan-Tan commented on Jul 23, 2019

@Sihan-Tan

errorCaptured

zhaofeipeter

zhaofeipeter commented on Aug 2, 2020

@zhaofeipeter

errorHandler

jiefancis

jiefancis commented on Aug 16, 2022

@jiefancis

Vue.config.errorHandler = function (err, vm, info) {} 捕获所有组件
errorCaptured
捕获当前组件的后代组件的错误

sc950828

sc950828 commented on Sep 23, 2022

@sc950828

全局: errorhandler
组件内:errorCaptured

Cai-zhiji

Cai-zhiji commented on Jul 7, 2023

@Cai-zhiji

全局错误处理

可以通过Vue的config.errorHandler方法来注册全局错误处理器,用于捕获整个应用程序范围内的未捕获的错误。
在全局错误处理器中,你可以记录错误信息、发送错误报告或执行其他自定义的错误处理逻辑。

Vue.config.errorHandler = function(err, vm, info) {
  // 处理错误,例如发送错误报告
  console.error('Global Error:', err, vm, info);
};

组件错误边界

Vue 2.x并没有内置的组件级错误处理机制,但你可以使用Vue的errorCaptured钩子函数来捕获并处理单个组件内的错误。
在组件中定义errorCaptured钩子函数,用于捕获该组件及其子组件中发生的错误。
在errorCaptured钩子函数中,你可以对错误进行处理、展示错误信息或展示备用的UI内容。

Vue.component('my-component', {
  // ...
  errorCaptured: function(err, vm, info) {
    // 处理错误,例如展示错误信息
    console.error('Component Error:', err, vm, info);
    // 返回 `false` 以阻止错误继续向上冒泡
    return false;
  },
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@zhaofeipeter@sc950828@jiefancis@Sihan-Tan

        Issue actions

          [vue] 怎么捕获组件vue的错误信息? · Issue #327 · haizlin/fe-interview