This week, I checked some articles about vue global exception handling, and I have made some modifications according to my own needs. I will record it here.
This global exception handling is just a preliminary template, mainly doing several things:
Customized new error type ServiceError.
Overrides Vue’s global exception handling interface (Vue.config.errorHandler), using the custom given errorHandler.
Before the component is loaded, use beforeCreate hook to traverse all methods. If it is a normal function, it will return directly. If it is a Promise function, call the custom errorHandler function in the catch function.
Through the above points, all exceptions that are not caught and handled by us will go to the errorHandler function.
So what does this errorHandler function do?
Determine whether it is our custom error type ServiceError, if so, pop up the ElementUI message component, the content is ServiceError errorMessage.
If it is a normal error, simply print it in Console.
Finally see if the page has a function to reset the state, if there is, then execute, otherwise execute the default state reset function, the current function is just to cancel the loading state.
At present, it is just a relatively simple version, the purpose is just to not get the page stuck in the loading state if an uncaught exception occurs, and if it is a custom error, we can customize how to handle it.
If you communicate with the background through Axios, you can also declare the api as a method alone, so that once the whole method is 500, it will not affect the execution of the next function, such as:
The method that originally needed to be written like this
This not only looks more comfortable, there are not so many Code Block nesting, but even if this. $_warning (this. $t (‘tips.refreshFailed’)); error occurs, the errorHandler will help us cancel the loading state.
In short, it is an attempt to catch vue global exceptions, which is still being improved.