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.
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:
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.
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.
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.
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.
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.
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.
There are four main types of errors you’re likely to encounter in your Vue.js app:
Now let’s zoom in on some specific examples of error handling and debugging activities you can perform with Vue Debugger.
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"); } }
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 VuexUsing 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;
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>
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>
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.
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.
LogRocket is like a DVR for web and mobile 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 — start monitoring for free.
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowDesign React Native UIs that look great on any device by using adaptive layouts, responsive scaling, and platform-specific tools.
Angular’s two-way data binding has evolved with signals, offering improved performance, simpler syntax, and better type inference.
Fix sticky positioning issues in CSS, from missing offsets to overflow conflicts in flex, grid, and container height constraints.
From basic syntax and advanced techniques to practical applications and error handling, here’s how to use node-cron.