Selaa lähdekoodia

Add handleError during event handling (#5709)

* Add handleError during event handling

Currently handleError is used to handle errors during lifecycle hooks.
This commit adds this functionality in to the event handling for
consistency.

* style tweak
Chris Nicola 9 vuotta sitten
vanhempi
commit
11b7d5dff2
2 muutettua tiedostoa jossa 27 lisäystä ja 3 poistoa
  1. 12 2
      src/core/instance/events.js
  2. 15 1
      test/unit/features/error-handling.spec.js

+ 12 - 2
src/core/instance/events.js

@@ -1,7 +1,13 @@
 /* @flow */
 
+import {
+  tip,
+  toArray,
+  hyphenate,
+  handleError,
+  formatComponentName
+} from '../util/index'
 import { updateListeners } from '../vdom/helpers/index'
-import { toArray, tip, hyphenate, formatComponentName } from '../util/index'
 
 export function initEvents (vm: Component) {
   vm._events = Object.create(null)
@@ -121,7 +127,11 @@ export function eventsMixin (Vue: Class<Component>) {
       cbs = cbs.length > 1 ? toArray(cbs) : cbs
       const args = toArray(arguments, 1)
       for (let i = 0, l = cbs.length; i < l; i++) {
-        cbs[i].apply(vm, args)
+        try {
+          cbs[i].apply(vm, args)
+        } catch (e) {
+          handleError(e, vm, `event handler for "${event}"`)
+        }
       }
     }
     return vm

+ 15 - 1
test/unit/features/error-handling.spec.js

@@ -11,7 +11,8 @@ describe('Error handling', () => {
     ['beforeCreate', 'beforeCreate hook'],
     ['created', 'created hook'],
     ['beforeMount', 'beforeMount hook'],
-    ['directive bind', 'directive foo bind hook']
+    ['directive bind', 'directive foo bind hook'],
+    ['event', 'event handler for "e"']
   ].forEach(([type, description]) => {
     it(`should recover from errors in ${type}`, done => {
       const vm = createTestInstance(components[type])
@@ -215,6 +216,19 @@ function createErrorTestComponents () {
     }
   }
 
+  // event errors
+  components.event = {
+    beforeCreate () {
+      this.$on('e', () => { throw new Error('event') })
+    },
+    mounted () {
+      this.$emit('e')
+    },
+    render (h) {
+      return h('div')
+    }
+  }
+
   return components
 }