Solomon Eseme I am a software developer who is geared toward building high-performing and innovative products following best practices and industry standards. I also love writing about it at masteringbackend.com. Follow me on Twitter @kaperskyguru, on Facebook, onLinkedIn, and on About.Me at Solomon Eseme." Follow me: Twitter, Facebook, LinkedIn, about.me

Error handling, debugging, and tracing in Vue.js

4 min read 1343

Error Handling, Debugging, and Tracing in Vue.js

In software development, things are not as smooth as they may seem to the user. There are always errors and bugs that developers must deal with behind the scenes. As you might imagine, debugging and error tracing can be time-consuming, and the tools you use can make a huge difference in productivity.

If you’re using Vue.js, you’ve surely encountered various types of errors, and there’s usually more than one way to handle them. In this tutorial, we’ll review some best practices and demonstrate how to handle errors, set up a debugger, and trace errors efficiently in Vue.js.

We’ll use Vue CLI to set up our demo project, a to-do app that displays a list of items from the Placeholder API.

The full code for this project is available on GitHub.

What is error handling?

Error handling refers to the process of tracing, handling, and resolving application errors without negatively affecting the user experience. It aims to accomplish three objectives:

  1. Prevent the application from breaking unexpectedly in production when there’s an unhandled exception
  2. Discover what happened when an error is logged
  3. Improve the user experience (e.g., by displaying messages when bugs are discovered and fixed)

What is debugging?

Debugging is the process of identifying and removing errors and resolving bugs in software. It involves analyzing a problem, identifying its origin, determining the cause, and charting a course to resolve it as efficiently as possible.

Debugging in Vue.js

Vue.js provides a debugger that helps you handle errors and quickly address bugs in your application. VueJs Debugger is well-integrated with VSCode and both Chrome and Firefox.

First, download and install the Vue Debugger extension for Chrome or Firefox. You can read more on how to configure it in the Vue.js docs.

Once you’ve installed the debugger, go to VSCode Activity Bar and click the debugging icon. You’ll see a gear/settings icon. Click it and select your preferred browser.

Next, open the launch.json file and paste in the corresponding configuration based on the browser you selected.

We made a custom demo for .
No really. Click here to check it out.

Once the setup is complete, tracing errors is as easy as setting up several breakpoints in your application and running the debugger you just installed.

What is tracing?

Tracing is the process of searching for the origin of an error and identifying the cause in a stack trace.

As you might’ve guessed, Vue Debugger also makes tracing a lot easier.

Setting up a breakpoint

Before you can achieve effective tracing, you need to learn how to set up a breakpoint.

Double-click on the line number in your VSCode to add a breakpoint. Then, run npm run serve to serve your project. Go to the debug view in your editor and select your preferred browser configuration. Press 5 or click the green play button. At this point, your breakpoints should hit when the code executes.

If you look at the debug view, you can spot some useful data for debugging your application.

Debugging Data in VS Code

Handling errors in Vue.js

Handling errors in a Vue.js application can be complicated. The best approach is to break it into steps.

In any application I develop, I always formulate a plan for handling errors, usually by creating a generic ErrorService class and including functions to handle and process the errors coming in according to their type.

Types of errors

There are four main types of errors you’re likely to encounter in your Vue.js app:

  1. Syntax errors occur when you use the wrong syntax
  2. Runtime errors are caused by illegal operations during execution
  3. Logical errors are difficult to identify because they result from mistakes in the program logic
  4. HTTP errors are common when you’re working with APIs

Now let’s zoom in on some specific examples of error handling and debugging activities you can perform with Vue Debugger.

Create an error service in Vue.js

The ErrorService class will handle all your errors and decide how to process them.

import Swal from "sweetalert2";
import "sweetalert2/dist/sweetalert2.min.css";

export default class ErrorService {
  constructor() {
    // this.initHandler();
  }

  static onError(error) {
    const response = error.response;
    if (response && response.status >= 400 && response.status < 405) {
      // You can handle this differently
      ErrorService.sentryLogEngine(error);
      return false;
    }
    // Send Error to Log Engine e.g LogRocket
    ErrorService.logRocketLogEngine(error);
  }

  static onWarn(error) {
    // Send Error to Log Engine e.g LogRocket
    this.logRocketLogEngine(error);
  }

  static onInfo(error) {
    // You can handle this differently
    this.sentryLogEngine(error);
  }

  static onDebug(error) {
    const response = error.response;
    if (response && response.status >= 400 && response.status < 405) {
      // You can handle this differently
      this.sentryLogEngine(error);
      return false;
    }
    // Send Error to Log Engine e.g LogRocket
    this.logRocketLogEngine(error);
  }

  static initHandler() {
    const scope = this;
    window.onerror = (message, url, lineNo, columnNo, error) => {
      console.log(error, "test");
      if (error) {
        scope.onError(error);
        console.log(message, url, lineNo, columnNo, error);
      }
    };
  }

  static displayErrorAlert(message) {
    Swal.fire({
      title: "Error!",
      text: message,
      icon: "error",
    });
  }

  static logRocketLogEngine(error) {
    // Implement LogRocket Engine here
    console.log(error, "LogRocket");
  }

  static sentryLogEngine(error) {
    // Implement Sentry Engine here
    console.log(error, "Sentry");
  }
}

Catch all possible Vue errors

Vue.js offers an error handler to catch all possible Vue errors. You can do this inside the main.js file.

import Vue from "vue";
import App from "./App.vue";
import { ErrorService } from "./Services/ErrorService";
import store from "./store";

Vue.config.productionTip = false;

// Handle all Vue errors
Vue.config.errorHandler = (error) => ErrorService.onError(error);

new Vue({
  store,
  render: (h) => h(App),
}).$mount("#app");

ErrorService in Vuex

Using the ErrorService class in Vuex is a great way to handle and process HTTP errors from Axios. You can also store the errors in Vuex State so they can be displayed to the user gracefully.

import Vue from "vue";
import Vuex from "vuex";
import { ErrorService } from "./Services/ErrorService";
import axios from "axios";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    todos: [],
    errors: [],
    users: [],
  },

  actions: {
    async getTodos({ commit }) {
      try {
        const response = await axios.get(
          `https://jsonplaceholder.typicode.com/todos`
        );
        const { data } = response;
        commit("STORE_TODOS", data);
      } catch (error) {
        // Handling HTTPs Errors
        commit("STORE_ERRORS", error);
      }
    },

    async getUsers({ commit }) {
      try {
        const response = await axios.get(
          `https://jsonplaceholder.typicode.com/users`
        );
        const { data } = response;
        commit("STORE_USERS", data);
      } catch (error) {
        // Handling HTTPs Errors
        commit("STORE_ERRORS", error);
      }
    },
  },

  mutations: {
    STORE_TODOS: (state, data) => {
      state.todos = data;
    },

    STORE_ERRORS: (state, error) => {
      // Call Error Service here
      ErrorService.onError(error);
      ErrorService.initHandler();

      // Store error to state(optional)
      if (error.response) {
        state.errors = error.response;
      }
    },

    STORE_USERS: (state, data) => {
      state.users = data;
    },
  },

  getters: {
    getTodo: (state) => (id) => {
      return state.todos.find((todo) => todo.id == id);
    },
    getUser: (state) => (id) => {
      return state.users.find((user) => user.id == id);
    },
  },

  // strict: true
});

export default store;

Displaying errors in a component

Since the errors are saved in the Vuex State, which enables us to leverage the reactivity of Vue, we can display them on the error component like so:

<script>
import { mapGetters } from "vuex";
import ErrorService from "../Services/ErrorService";

export default {
  name: "HelloWorld",
  props: {
    todo: Object,
  },
  computed: {
    ...mapGetters(["getUser"]),
  },

  methods: {
    getUserName(id) {
      const user = this.getUser(id);
      if (user) return user.username;
    },

    // Handling Errors in component
    methodThrowsException() {
      try {
        // Do unexpected job
      } catch (error) {
        ErrorService.onError(error);
      }
    },
  },
};
</script>

Displaying errors with plugins in Vue.js

You can display these errors to the user in different ways. We’ll use the vue-sweetalert2 plugin to display our errors.

<script>
import { mapGetters } from "vuex";
import ErrorService from "../Services/ErrorService";

export default {
  name: "HelloWorld",
  props: {
    todo: Object,
  },
  computed: {
    ...mapGetters(["getUser"]),
  },

  methods: {
    getUserName(id) {
      const user = this.getUser(id);
      if (user) return user.username;
    },

    // Display Error with SweetAlert (when Name is Click)
    displayAlert() {
      ErrorService.displayErrorAlert("Testing message");
    },
  },
};
</script>

Conclusion

The ability to handle errors and resolve bugs in your application efficiently is crucial. If you want to maximize your productivity, choosing the right tools and methods for debugging your Vue.js app can make a huge difference.

Hopefully, this walkthrough gave you a solid, foundational understanding of error management, debugging, and tracing in VueJS.

Experience your Vue apps exactly how a user does

Debugging Vue.js applications can be difficult, especially when there are dozens, if not hundreds of mutations during a user session. If you’re interested in monitoring and tracking Vue mutations for all of your users in production, try LogRocket. https://logrocket.com/signup/

LogRocket is like a DVR for web apps, recording literally everything that happens in your Vue apps including network requests, JavaScript errors, performance problems, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.

The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, giving you context around what led to an error, and what state the application was in when an issue occurred.

Modernize how you debug your Vue apps - .

Solomon Eseme I am a software developer who is geared toward building high-performing and innovative products following best practices and industry standards. I also love writing about it at masteringbackend.com. Follow me on Twitter @kaperskyguru, on Facebook, onLinkedIn, and on About.Me at Solomon Eseme." Follow me: Twitter, Facebook, LinkedIn, about.me

Leave a Reply