How to implement global error handling in Vue How to implement global error handling in Vue vue.js vue.js

How to implement global error handling in Vue


As @Badgy mentioned you can install a Vue error handler to catch errors Vue encounters. This can be done as follows:

 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+ }

The above code can be located anywhere you like in your javascript. I locate the code just before I create my vue instance. i.e before my var app = new Vue({...}); code. Because it's a global vue error handler it will handle errors from all instances of vue as well as vue components. I find that in practice it mostly catches errors that occur in the vue render methods.

You can read more about it in the official docs here: https://vuejs.org/v2/api/#errorHandler

For more general (non vue related) javascript errors you still need a global error handler like so:

 window.onerror = function (msg, url, line, col, error) {     //code to handle or report error goes here }

Again, this code can be placed anywhere javascript is allowed but typically you will want to place it to run early in your javascript stack. You can read more about this here: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror

And finally, to catch a "Promise rejection" (i.e. an exception throw from a Promise function) we need to listen for unhandledrejection events since a Promise rejection is not caught by the window.onerror mechanism (thanks to @Blauhirn for the tip). In some browsers (Chrome and Edge currently) Promise rejections can be caught with the following approach:

 window.addEventListener('unhandledrejection', function(event) {     //handle error here     //event.promise contains the promise object     //event.reason contains the reason for the rejection });

For more info see this StackOverflow question: Catch all unhandled javascript promise rejections


I hope i understood your Question Right, but this could be what you are Looking for.

errorCaptured

Type: (err: Error, vm: Component, info: string) => ?boolean

Details: Called when an error from any descendent component is captured. The hook receives three arguments: the error, the component instance that triggered the error, and a string containing information on where the error was captured. The hook can return false to stop the error from propagating further.

Here is more in-Depth Info About it.Be careful its Vue 2.5.0+