Error tracking with Vue.js
Tags: vue, javascript, errors
Published: 2018-08-14 17:10:57

---
title: Error tracking with Vue.js
published: true
tags: #vue, #javascript, #errors
description: 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: https://thepracticaldev.s3.amazonaws.com/i/h5puqudwgfofpm1ts8lu.png
canonical_url: https://rollbar.com/blog/error-tracking-vue-js/
---

[Vue (pronounced /vjuː/, like ](https://vuejs.org/v2/guide/index.html)[**view**](https://vuejs.org/v2/guide/index.html)[)](https://vuejs.org/v2/guide/index.html) 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](https://vuejs.org/v2/guide/deployment.html) and[ supporting libraries](https://github.com/vuejs/awesome-vue#components--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.

![Rollbar loves Vue.js](https://thepracticaldev.s3.amazonaws.com/i/h5puqudwgfofpm1ts8lu.png)

<!--more-->

## How to handle errors in vanilla Vue

You can catch exceptions in vanilla JavaScript using basic [try, catch and finally](https://www.w3schools.com/js/js_errors.asp) statements. You can use these statements to handle caught exceptions in Vue components. In this example, we are simply logging to the console.

```js
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.

```js
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.

```js
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](https://docs.rollbar.com/docs/javascript/) 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](https://rollbar.com/error-tracking/javascript/).

Below, you can see that we’ve created an [example app](https://github.com/RollbarExample/Rollbar-Vue-Example) 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](https://thepracticaldev.s3.amazonaws.com/i/8lutehzjylznm03orlbl.gif)

## How to set up a Vue project on Rollbar

1. Visit [https://rollbar.com](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 SDK 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.

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

2. 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.

```js        
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'
            }
       }
     }
});
```

3. Finally, add the Rollbar error reporting method in the error handler.

```js
Vue.rollbar.error(err);
```

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

```js
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,Vue.config.errorHandler= err => {
   Vue.rollbar.error(err);
 })
})
```

## Upload Source Maps to Rollbar
If you use Javascript, 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](https://docs.rollbar.com/docs/source-maps/) API call in your deployment script. Here is an example using `curl`:

```js
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.

```js
<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 ':'"

![Screenshot of Rollbar Vue error item](https://thepracticaldev.s3.amazonaws.com/i/r93nby1v4dy2cbj5zp73.png)

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.

![Screenshot of Rollbar Vue error detail](https://thepracticaldev.s3.amazonaws.com/i/suek2dx3ts22iaeoysvs.png)

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](https://rollbar.com/signup/) of Rollbar.