Paul
Paul

Reputation: 161

Vue JS How to catch errors globally and display them in a top level component

I have set up Vue so that I have a top level AppLayout component which just includes a Navigation Menu component, the router-view and, which uses v-if to optionally display an ErrorDisplay component if the error data item is set. I set this from an err state variable in the Vuex store.

That is where I want to get to. However, I think the problem is more fundamental.

In a lower component, I have a submit function that gets called when I click the submit button. To test error handling I have put

throw new Error('Cannot Submit');

In my Main.js I have

handlers for window.orerror, window.addEventListner, Vue.config.errorhandler, Vue.config.warnhandler

All of these should just call the errHandler function, which just calls an action to update the err variable in the state. The hope being that this will then result in the ErrorDisplay component showing on my top level component.

However, I have console.log statements as the first statement in all the above handlers and in my errHandler function. None of these console.logs are getting executed.

In the Console in Chrome, I am just seeing [vue warn]: Error in v-on handler: "Error: Cannot Submit"

So it is getting the text from my throw, but none of the error handlers seem to be capturing this?

Upvotes: 2

Views: 10109

Answers (2)

Varit J Patel
Varit J Patel

Reputation: 3520

Vue provides Global configuration config.errorHandler to capture error inside Vue components Globally.

As per Official Docs

Assign a handler for uncaught errors during component to render function and watchers. The handler gets called with the error and the Vue instance.

This is how it can be used:

Vue.config.errorHandler = function (err, vm, info) {
  // handle error
  // `info` is a Vue-specific error info, e.g. which lifecycle hook
  // the error was found in. Only available in 2.2.0+
}

Official docs

Hope this helps!

Upvotes: 2

Paul
Paul

Reputation: 161

Did more research and I think someone may have already raised a bug report with Vue for this PR on Vue https://github.com/vuejs/vue/pull/5709

So it looks like the problem is that the way that I am trying to test this isn't being caught.

Upvotes: 0

Related Questions