UNPKG

2.19 kBJavaScriptView Raw
1/* @flow */
2
3import config from '../config'
4import { warn } from './debug'
5import { inBrowser, inWeex } from './env'
6import { isPromise } from 'shared/util'
7import { pushTarget, popTarget } from '../observer/dep'
8
9export function handleError (err: Error, vm: any, info: string) {
10 // Deactivate deps tracking while processing error handler to avoid possible infinite rendering.
11 // See: https://github.com/vuejs/vuex/issues/1505
12 pushTarget()
13 try {
14 if (vm) {
15 let cur = vm
16 while ((cur = cur.$parent)) {
17 const hooks = cur.$options.errorCaptured
18 if (hooks) {
19 for (let i = 0; i < hooks.length; i++) {
20 try {
21 const capture = hooks[i].call(cur, err, vm, info) === false
22 if (capture) return
23 } catch (e) {
24 globalHandleError(e, cur, 'errorCaptured hook')
25 }
26 }
27 }
28 }
29 }
30 globalHandleError(err, vm, info)
31 } finally {
32 popTarget()
33 }
34}
35
36export function invokeWithErrorHandling (
37 handler: Function,
38 context: any,
39 args: null | any[],
40 vm: any,
41 info: string
42) {
43 let res
44 try {
45 res = args ? handler.apply(context, args) : handler.call(context)
46 if (res && !res._isVue && isPromise(res) && !res._handled) {
47 res.catch(e => handleError(e, vm, info + ` (Promise/async)`))
48 // issue #9511
49 // avoid catch triggering multiple times when nested calls
50 res._handled = true
51 }
52 } catch (e) {
53 handleError(e, vm, info)
54 }
55 return res
56}
57
58function globalHandleError (err, vm, info) {
59 if (config.errorHandler) {
60 try {
61 return config.errorHandler.call(null, err, vm, info)
62 } catch (e) {
63 // if the user intentionally throws the original error in the handler,
64 // do not log it twice
65 if (e !== err) {
66 logError(e, null, 'config.errorHandler')
67 }
68 }
69 }
70 logError(err, vm, info)
71}
72
73function logError (err, vm, info) {
74 if (process.env.NODE_ENV !== 'production') {
75 warn(`Error in ${info}: "${err.toString()}"`, vm)
76 }
77 /* istanbul ignore else */
78 if ((inBrowser || inWeex) && typeof console !== 'undefined') {
79 console.error(err)
80 } else {
81 throw err
82 }
83}