1 |
|
2 |
|
3 | import config from '../config'
|
4 | import { warn } from './debug'
|
5 | import { inBrowser, inWeex } from './env'
|
6 | import { isPromise } from 'shared/util'
|
7 |
|
8 | export function handleError (err: Error, vm: any, info: string) {
|
9 | if (vm) {
|
10 | let cur = vm
|
11 | while ((cur = cur.$parent)) {
|
12 | const hooks = cur.$options.errorCaptured
|
13 | if (hooks) {
|
14 | for (let i = 0; i < hooks.length; i++) {
|
15 | try {
|
16 | const capture = hooks[i].call(cur, err, vm, info) === false
|
17 | if (capture) return
|
18 | } catch (e) {
|
19 | globalHandleError(e, cur, 'errorCaptured hook')
|
20 | }
|
21 | }
|
22 | }
|
23 | }
|
24 | }
|
25 | globalHandleError(err, vm, info)
|
26 | }
|
27 |
|
28 | export function invokeWithErrorHandling (
|
29 | handler: Function,
|
30 | context: any,
|
31 | args: null | any[],
|
32 | vm: any,
|
33 | info: string
|
34 | ) {
|
35 | let res
|
36 | try {
|
37 | res = args ? handler.apply(context, args) : handler.call(context)
|
38 | if (isPromise(res)) {
|
39 | res.catch(e => handleError(e, vm, info + ` (Promise/async)`))
|
40 | }
|
41 | } catch (e) {
|
42 | handleError(e, vm, info)
|
43 | }
|
44 | return res
|
45 | }
|
46 |
|
47 | function globalHandleError (err, vm, info) {
|
48 | if (config.errorHandler) {
|
49 | try {
|
50 | return config.errorHandler.call(null, err, vm, info)
|
51 | } catch (e) {
|
52 | logError(e, null, 'config.errorHandler')
|
53 | }
|
54 | }
|
55 | logError(err, vm, info)
|
56 | }
|
57 |
|
58 | function logError (err, vm, info) {
|
59 | if (process.env.NODE_ENV !== 'production') {
|
60 | warn(`Error in ${info}: "${err.toString()}"`, vm)
|
61 | }
|
62 |
|
63 | if ((inBrowser || inWeex) && typeof console !== 'undefined') {
|
64 | console.error(err)
|
65 | } else {
|
66 | throw err
|
67 | }
|
68 | }
|