Vue 错误处理

11/9/2022 VueJavaScript

错误处理也是开发中的重要环节,通过一个小例子展示 Vue 框架内部对错误的处理。假设开发一个工具函数 foo。

// utils
function foo(fn) {
  fn && fn()
}
1
2
3
4

当调用 foo 函数发生错误时,可以让用户自行处理,使用 try...catch 捕获错误。当如果有多个函数,则需要用户写多个处理程序。为了减少用户负担,可以封装函数统一处理错误。

// utils
function foo(fn) {
  callWithErrorHandler(fn)
}
function callWithErrorHandler(fn) {
  try {
    fn()
  } catch(e) {
    console.log(e)
  }
}
1
2
3
4
5
6
7
8
9
10
11

我们还可以为用户提供统一的错误处理接口。

// utils
let handleError = null
export default {
  foo(fn) {
    callWithErrorHandler(fn)
  },
  registerErrorHandler(fn) {
    handleError = fn
  }
}
function callWithErrorHandler(fn) {
  try {
    fn()
  } catch(e) {
    handleError(e)
  }
}

// 调用
registerErrorHandler(e => {
  console.log(e)
})
foo(() => console.log('Hello World'))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Last Updated: 12/21/2022, 4:35:16 PM