DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Serving a Vue.js Application With a Go Backend
  • Leveraging Salesforce Using a Client Written In Vue.js
  • How to Integrate Vue.js Applications With Drupal
  • Vue.js Tutorial: Build a Tesla Battery Range Calculator in Vue 3

Trending

  • How to Convert XLS to XLSX in Java
  • Measuring the Impact of AI on Software Engineering Productivity
  • AI's Dilemma: When to Retrain and When to Unlearn?
  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  1. DZone
  2. Coding
  3. JavaScript
  4. Error Tracking With Vue.js

Error Tracking With Vue.js

In this article, we’ll show you how to add error handling in a Vue.js-based application to capture caught and uncaught errors.

By 
Jason Skowronski user avatar
Jason Skowronski
·
Aug. 22, 18 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
13.4K Views

Join the DZone community and get the full member experience.

Join For Free

Vue (pronounced /vjuː/, like view) is a progressive framework for building user interfaces on the web. Vue can power sophisticated single-page applications and is often used in combination with modern tooling and supporting libraries. We’ll show you how to add error handling in a Vue application to capture caught and uncaught errors. This gives you an opportunity to recover and update what’s presented to the user, as well as track the error to prioritize fixes. We’ll also show how to monitor errors in production using Rollbar.

Image title

How to Handle Errors in Vanilla Vue

You can catch exceptions in vanilla JavaScript using basic try, catch and finally statements. You can use these statements to handle caught exceptions in Vue components. In this example, we are simply logging to the console.

try {
  JSON.parse("non-JSON data")
} catch(e) {
  console.log('Exception: ', e)
}

Vue provides a standard API to add a custom errorHandler. You should configure this on your root Vue instance, typically in a main.js file. However, it only captures errors that occur during component rendering. That means it won’t catch errors that happen later as a result of user behavior, etc.

Vue.config.errorHandler = err => {
  console.log('Exception: ', err)
}

To handle errors globally across your entire page, you can add a handler to the onerror function on the window.

window.onerror = function(message, source, lineno, colno, error) {
  console.log('Exception: ', error)
}

While this is great for handling errors during development, when you deploy to production you need a way to track those errors centrally to determine how they are affecting user experience.

Monitor Vue Errors With Rollbar

Errors logged to the console are less useful in a production environment because your developers won’t have access to them. It’s important to monitor errors centrally so you can fix them before more customers are affected. This can help prioritize high impact errors and troubleshoot the causes faster.

Rollbar’s JavaScript SDK lets you track and analyze errors that happen in your Vue applications, including detailed stack traces, request params, telemetry on user behavior, affected users, and more. This helps developers quickly identify and fix errors. Learn more about Rollbar’s JavaScript features.

Below, you can see that we’ve created an example app that triggers an exception when the user clicks on a button. The error message is tracked in Rollbar, including a stack trace where you can see the line of code that caused the error. Rollbar captures errors that occur anywhere in the app.

Screenshot of Rollbar Vue Error

How to Set up a Vue Project on Rollbar

  1. Visit https://rollbar.com and sign up for an account if you haven’t done so yet. Next, create your project and select 'Other' from the list of notifiers. Select the client side access token that is generated for you. You’ll need this to configure Rollbar in the steps below.
  2. To install the vue-rollbar plugin in your project through npm, open the command prompt in the project root directory and run the command below.
npm install vue-rollbar --save

Adding Rollbar in the Error Handler

To add Rollbar to your Vue application, you need to follow some simple steps.

  1. Add Rollbar in the main.js file. You can find main.js file under the src folder in your root project directory.
var Rollbar = require('vue-rollbar');
  1. Next, you need to use Rollbar with an access token and some optional parameters. Here we've set captureUncaught to true, so we don't even need to wire an event handler to the onerror function. Rollbar does this automatically.
Vue.use(Rollbar, {
     accessToken: 'ACCESS-TOKEN’',
     captureUncaught: true,
     captureUnhandledRejections: true,
     enabled: true,
     source_map_enabled: true,
     environment: 'production',
     payload: {
       client: {
            javascript: {
               code_version: '1.0'
            }
       }
     }
});
  1. Finally, add the Rollbar error reporting method in the error handler.
Vue.rollbar.error(err);

After adding the Rollbar error reporting method, the main.js file looks like this:

import Vue from 'vue'
import App from './App'
import router from './router'

var Rollbar = require('vue-rollbar');

Vue.config.productionTip = false;

Vue.use(Rollbar, {
     accessToken: 'ACCESS-TOKEN',
     captureUncaught: true,
     captureUnhandledRejections: true,
     enabled: true,
     source_map_enabled: true,
     environment: 'production',
     payload: {
       client: {
            javascript: {
               code_version: '1.0'
            }
       }
     }
});

new Vue({
 el: '#app',
 router,
 render: h => h(App)
})

Upload Source Maps to Rollbar

If you use JavasScript, Rollbar can map the error message back to your original source code using source maps. Source maps are essential to debugging production code. They link the browser’s debug output back to the original source code before it was minified or transpiled. To display stack traces with your original code, Rollbar needs access to the source maps for your minified JavaScript.

To upload the source map, you need to add a Rollbar source map API call in your deployment script. Here is an example using curl:

curl https://api.rollbar.com/api/1/sourcemap/ \
     -F access_token=’SERVER-ACCESS-TOKEN’\
     -F version=’1.0’ \
     -F minified_url=https://s3.us-east-2.amazonaws.com/rollbar-example/app.[hash].js \
     -F source_map=dist/static/js/app.[hash].js.map \
     -F App.vue=App.vue \
     -F HelloWorld.vue=HelloWorld.vue

The parameters in this API call are:

  • access_token: The destination project token on Rollbar. This token is generated when a project is created on Rollbar.
  • environment: The deployment environment where the service is deployed. We can configure different environments such as development, staging, and production.
  • version: The deployed application version. Rollbar will create a link to the repository commit source code if the supplied version is the commit ID.
  • minified_url: The full URL of the minified file. It should start with http: or https:, which we’ll strip off.
  • source_map: The contents of the source map, as a multipart file upload.

Testing the Sample Application

To test that it’s working, create a page that will generate an error message. In the example below, you’ll be able to generate an error by clicking the "Generate an error" button.

<template>
  <div class="hello">
    <h1>Rollbar Vue Example</h1>
    <ul>
      <li>
        <button v-on:click="parse">Generate an error</button>
      </li>
    </ul>
  </div>
</template>

<script>
  import Vue from 'vue'
  export default {
    name: 'HelloWorld',
    props: {
      msg: 'Rollbar Example'
    },
    data: () => ({
      clicks: 0,
      json: '{ "not quite: json" }'
    }),
    methods: {
      parse: function () {
        JSON.parse(this.json)  // SyntaxError: JSON.parse:  
      }
    }          
  }
</script>

Viewing Errors in Rollbar

Open Rollbar to see what these errors look like in your account’s item page. The error we just generated should be called "SyntaxError: JSON.parse: expected ':'"

Image title

Get more details by clicking on the item. You can now see a traceback showing you the exact source code file, method, and line number that generated the error.

Image title

Now that you have Rollbar integrated into your Vue app, any errors that occur will be captured, grouped, and reported to Rollbar. You’ll be able to quickly and easily see which errors are occurring, how often they occur, as well as the full context. This will help you troubleshoot the cause faster and fix the problem so fewer customers are affected. If you haven’t already, sign up for a 14-day free trial of Rollbar.

application Vue.js

Published at DZone with permission of Jason Skowronski, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Serving a Vue.js Application With a Go Backend
  • Leveraging Salesforce Using a Client Written In Vue.js
  • How to Integrate Vue.js Applications With Drupal
  • Vue.js Tutorial: Build a Tesla Battery Range Calculator in Vue 3

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!