Building front-end applications is not as easy as it used to be, and applications are now more complex and diverse. This requires a lot of consideration when building front-end applications, with error/exception handling being one of the most important aspects. There are many benefits to having good error handling in your application, such as:

  • Good error handling prevents your application from crashing in the event of an unhandled exception
  • In a production environment, error logging can be easily stored or tracked for exception handling
  • Error messages can be handled uniformly, for example by changing the UI for displaying error messages without breaking the application interaction
  • Helps improve the user experience

In front end applications, the most common types of errors/exceptions might include the following:

  • Syntax errors: Some incorrect syntax was used
  • Runtime error: due to an illegal operation during execution
  • Logic error: Due to a program logic error
  • Http error: Error returned by the API

There are many ways to solve this problem, such as using ESLint to check for syntax errors, using appropriate try-catch statements to handle run-time errors, minimizing logic errors with appropriate single-page or integration tests, and using PROMISES to handle HTTP errors.

The implementation scheme of front-end exception monitoring was briefly introduced in the article “Brief Introduction to the Implementation Scheme of front-end Exception Monitoring Platform”. In this paper, an error/exception handling mechanism in Vue application is recommended.

Global configuration

A Vue application has a global configuration, vue.config, that can be configured to disable logging and alerting, devtools, error handlers, and so on.

You can override these configurations with your own, and for error handling, you can assign a handler function, vue.config.errorHandler. This handler is called by any uncaught exception in any Vue instance (Vue component) throughout the application. The following code snippet registers an error handling method for a Vue application (typically in the project’s main.js file) :

/** ** @param {*} error Error tracking * @param {*} VM component error * @param {*} info Specific error information such as lifecycle hooks, events, etc. */ Vue.config.errorHandler = (error, vm, info) => { console.info(error); console.info(vm); console.info(info); };Copy the code

The handler contains three parameters:

  • error: Complete error tracking, includingmessageerror stack
  • vm: The Vue component/instance where the error occurred
  • info: specific error messages such as lifecycle hooks, events, etc.

Vue.config.errorHandler catches errors specific to the Vue instance, but cannot catch errors outside the Vue instance, such as services.

To catch errors outside of the Vue instance, you can use the window.onError event, and you can register an error handler that will catch all unhandled exceptions that are not specific to the Vue instance. The following code snippet registers the window.onError exception handler for its application:

Window. onerror = function(message, source, lineno, colno, error) {// TODO: define trace logic};Copy the code

Custom exception components

Often projects have predictable exceptions that require a custom UI, and you can customize exception components to take over exception handling uniformly. If there is an exception, display the exception information, otherwise display the component information, the code is as follows:

<template> <div> <slot v-if="errors" name="errors"> <a-alert :message="errors.title" :description="errors.description" show-icon type="warning" class="mb-2" > </a-alert> </slot> <slot v-else></slot> </div> </template> <script> export Default {name: "QtErrorContainer", props: {errors: Object, // {title:"500 error ",description:" database connection timeout "}},}; </script>Copy the code

The above component acts as a container to load other components, such as pulling list data through the background interface, called as follows:

<QtErrorContainer :errors="errors">
    <a-table ></a-table>
</QtErrorContainer>
Copy the code

The above code displays the table component
when errors is null or false, otherwise it displays the exception information. The benefit of this implementation is that all predictable exceptions are handled by a uniform component, improving reuse and flexibility.

Log processing

For log processing, it can be encapsulated as a separate class, such as Logger, which is responsible for collecting all exception logs in the Vue and output them to the console or send them to the server for storage or third-party log tracking platform through the interface. The processing mode of Logger can be modified as follows:

import { environment } from "@/environment/"; /** * Logger */ class Logger {/** * @constructor AppLogger */ constructor() {this.init(); } init() { if (environment ! == "production") { this.log = console.log.bind(console); this.debug = console.debug.bind(console); this.info = console.info.bind(console); this.warn = console.warn.bind(console); this.error = console.error.bind(console); this.toServer = this.error; } else {/** In the case of production, replace the function definition */ this.log = this.debug = this.info = this.warn = this.error = () => {}; / / this.toserver = (err) => {console.error(err); }; } } } const logger = new Logger(); export { logger };Copy the code

You can reference the Logger class to the above global configuration handling method as follows:

import Vue from "vue"; import { logger } from "@/logger"; /** ** @param {*} error Error tracking * @param {*} VM component error * @param {*} info Specific error information such as lifecycle hooks, events, etc. */ Vue.config.errorHandler = (error, vm, info) => { logger.toServer({ error, vm, info }); }; window.onerror = function (message, source, lineno, colno, error) { logger.toServer({ message, source, lineno, colno, error }); };Copy the code

conclusion

Error handling is important for applications, and in this article, I’ve discussed vue.config. errorHandler using the global errorHandler of the lifecycle hook and custom components to handle predictable exceptions. This article provides the basic details that will make it easy to implement error handling for your application and document them, which will help create a better user experience.