Skip to content

rollbar/rollbar.js

Repository files navigation

Rollbar notifier for JavaScript Build Status

Quick start

Copy-paste the following code into the <head> of every page you want to monitor. It should be as high as possible, before any other <script> tags.

Be sure to replace POST_CLIENT_ITEM_ACCESS_TOKEN with your project's post_client_item access token, which you can find in the Rollbar.com interface.

<script>
var _rollbarConfig = {
    accessToken: "POST_CLIENT_ITEM_ACCESS_TOKEN",
    captureUncaught: true,
    payload: {
        environment: "production"
    }
};
// Rollbar Snippet
!function(r){function o(e){if(t[e])return t[e].exports;var n=t[e]={exports:{},id:e,loaded:!1};return r[e].call(n.exports,n,n.exports,o),n.loaded=!0,n.exports}var t={};return o.m=r,o.c=t,o.p="",o(0)}([function(r,o,t){"use strict";var e=t(1).Rollbar,n=t(2);_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||"https://d37gvrvc0wt4s1.cloudfront.net/js/vundefined/rollbar.min.js";var a=e.init(window,_rollbarConfig),i=n(a,_rollbarConfig);a.loadFull(window,document,!_rollbarConfig.async,_rollbarConfig,i)},function(r,o){"use strict";function t(){var r=window.console;r&&"function"==typeof r.log&&r.log.apply(r,arguments)}function e(r,o){return o=o||t,function(){try{return r.apply(this,arguments)}catch(t){o("Rollbar internal error:",t)}}}function n(r,o,t){window._rollbarWrappedError&&(t[4]||(t[4]=window._rollbarWrappedError),t[5]||(t[5]=window._rollbarWrappedError._rollbarContext),window._rollbarWrappedError=null),r.uncaughtError.apply(r,t),o&&o.apply(window,t)}function a(r){this.shimId=++p,this.notifier=null,this.parentShim=r,this.logger=t,this._rollbarOldOnError=null}function i(r){var o=a;return e(function(){if(this.notifier)return this.notifier[r].apply(this.notifier,arguments);var t=this,e="scope"===r;e&&(t=new o(this));var n=Array.prototype.slice.call(arguments,0),a={shim:t,method:r,args:n,ts:new Date};return window._rollbarShimQueue.push(a),e?t:void 0})}function l(r,o){if(o.hasOwnProperty&&o.hasOwnProperty("addEventListener")){var t=o.addEventListener;o.addEventListener=function(o,e,n){t.call(this,o,r.wrap(e),n)};var e=o.removeEventListener;o.removeEventListener=function(r,o,t){e.call(this,r,o&&o._wrapped?o._wrapped:o,t)}}}var p=0;a.init=function(r,o){var t=o.globalAlias||"Rollbar";if("object"==typeof r[t])return r[t];r._rollbarShimQueue=[],r._rollbarWrappedError=null,o=o||{};var i=new a;return e(function(){if(i.configure(o),o.captureUncaught){i._rollbarOldOnError=r.onerror,r.onerror=function(){var r=Array.prototype.slice.call(arguments,0);n(i,i._rollbarOldOnError,r)};var e,a,p="EventTarget,Window,Node,ApplicationCache,AudioTrackList,ChannelMergerNode,CryptoOperation,EventSource,FileReader,HTMLUnknownElement,IDBDatabase,IDBRequest,IDBTransaction,KeyOperation,MediaController,MessagePort,ModalWindow,Notification,SVGElementInstance,Screen,TextTrack,TextTrackCue,TextTrackList,WebSocket,WebSocketWorker,Worker,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload".split(",");for(e=0;e<p.length;++e)a=p[e],r[a]&&r[a].prototype&&l(i,r[a].prototype)}return r[t]=i,i},i.logger)()},a.prototype.loadFull=function(r,o,t,n,a){var i=function(){var o;if(void 0===r._rollbarPayloadQueue){var t,e,n,i;for(o=new Error("rollbar.js did not load");t=r._rollbarShimQueue.shift();)for(n=t.args,i=0;i<n.length;++i)if(e=n[i],"function"==typeof e){e(o);break}}"function"==typeof a&&a(o)},l=!1,p=o.createElement("script"),u=o.getElementsByTagName("script")[0],s=u.parentNode;p.src=n.rollbarJsUrl,p.async=!t,p.onload=p.onreadystatechange=e(function(){if(!(l||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState)){p.onload=p.onreadystatechange=null;try{s.removeChild(p)}catch(r){}l=!0,i()}},this.logger),s.insertBefore(p,u)},a.prototype.wrap=function(r,o){try{var t;if(t="function"==typeof o?o:function(){return o||{}},"function"!=typeof r)return r;if(r._isWrap)return r;if(!r._wrapped){r._wrapped=function(){try{return r.apply(this,arguments)}catch(o){throw o._rollbarContext=t()||{},o._rollbarContext._wrappedSource=r.toString(),window._rollbarWrappedError=o,o}},r._wrapped._isWrap=!0;for(var e in r)r.hasOwnProperty(e)&&(r._wrapped[e]=r[e])}return r._wrapped}catch(n){return r}};for(var u="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),s=0;s<u.length;++s)a.prototype[u[s]]=i(u[s]);r.exports={Rollbar:a,_rollbarWindowOnError:n}},function(r,o){"use strict";r.exports=function(r,o){return function(t){if(!t&&!window._rollbarInitialized){var e=window.RollbarNotifier,n=o||{},a=n.globalAlias||"Rollbar",i=window.Rollbar.init(n,r);i._processShimQueue(window._rollbarShimQueue||[]),window[a]=i,window._rollbarInitialized=!0,e.processPayloads()}}}}]);
// End Rollbar Snippet
</script>

If you're running Rollbar on an environment besides production, change the environment value to something else (e.g. "staging"). See below for more configuration options.

Test your installation

  1. Navigate your browser to a page that has the above code installed
  2. Type the following code into the console and press enter: window.onerror("TestRollbarError: testing window.onerror", window.location.href)

This simulates an uncaught error. It should appear in the Rollbar dashboard within a few seconds.

Usage

In addition to catching top-level errors, you can send caught errors or custom log messages. All of the following methods are fully-asynchronous and safe to call anywhere in your code after the <script> tag above.

// Caught errors
try {
  doSomething();
} catch (e) {
  Rollbar.error("Something went wrong", e);
}

// Arbitrary log messages. 'critical' is most severe; 'debug' is least.
Rollbar.critical("Connection error from remote Payments API");
Rollbar.error("Some unexpected condition");
Rollbar.warning("Connection error from Twitter API");
Rollbar.info("User opened the purchase dialog");
Rollbar.debug("Purchase dialog finished rendering");

// Can include custom data with any of the above.
// It will appear as `custom.postId` in the Occurrences tab
Rollbar.info("Post published", {postId: 123});

// Callback functions
Rollbar.error(e, function(err, data) {
  if (err) {
    console.log("Error while reporting error to Rollbar: ", e);
  } else {
    console.log("Error successfully reported to Rollbar. UUID:", data.result.uuid);
  }
});

To set configuration options at runtime, use Rollbar.configure:

// Set the person data to be sent with all errors for this notifier.
Rollbar.configure({
  payload: {
    person: {
      id: 456,
      username: "foo",
      email: "[email protected]"
    }
  }
});

(Advanced) For fine-grained control of the payload sent to the Rollbar API, use Rollbar.scope:

Rollbar.scope({fingerprint: "custom fingerprint to override grouping algorithm"}).error(err);

UMD / Browserify / Requirejs / Webpack

rollbar.js is also distributed using UMD, so you can use it with browserify, requirejs, webpack, or anything else that uses AMD or CommonJS modules. See the examples for details.

Disable reporting to rollbar.com

If you don't want to send data to Rollbar, just set the enabled flag to false for each notifier instance.

Rollbar.error("This will be reported to Rollbar");
Rollbar.configure({enabled: false});
Rollbar.error("This will *not* be reported to Rollbar");

Ignoring specific exception messages

If you want to ignore a specific exception message, say for a third-party browser plugin that is throwing errors, you can add the message to the ignoredMessages array, and Rollbar will ignore exceptions matching those messages.

var _rollbarConfig = {
  accessToken: "POST_CLIENT_ITEM_ACCESS_TOKEN",
  ignoredMessages: ["Can't find Clippy.bmp. The end is nigh."],
  captureUncaught: true,
  payload: {
    environment: "production"
  }
};
// init your rollbar like normal, or insert rollbar.js source snippet here

Verbose option

If you would like to see what is being sent to Rollbar in your console, use the verbose option.

var _rollbarConfig = {
  accessToken: "POST_CLIENT_ITEM_ACCESS_TOKEN",
  verbose: true, // This will now log to console.log, as well as Rollbar  
  captureUncaught: true,
  payload: {
    environment: "production"
  }
};
// init your rollbar like normal, or insert rollbar.js source snippet here

Synchronous option

By default, the snippet loads the full Rollbar source asynchronously. You can disable this which will cause the browser to download and evaluate the full rollbar source before evaluating the rest of the page.

More information can be found here: http:https://www.w3schools.com/tags/att_script_async.asp

var _rollbarConfig = {
  ...
  async: false,
  ...
};

Source Maps

If you minify your JavaScript in production, you'll want to configure source maps so you get meaningful stack traces. See the source maps guide for instructions.

iOS 9 Webviews

iOS 9 webviews will currently not work properly with the rollbar.js snippet above.

Starting with iOS 9, webviews will only allow connections to HTTPS hosts whose certificates are are signed using SHA256+ and whose key is either 2048+ bit RSA or 256+ ECC. Many CDNs, including Cloudfront, do not meet these specifications. More info here.

You have a couple of options to fix this behavior:

  • Update your app's Info.plist file to not enforce Forward Secrecy for the Rollbar cloudfront domain:
  <key>NSAppTransportSecurity</key> 
  <dict> 
    <key>NSExceptionDomains</key> 
    <dict> 
      <key>d37gvrvc0wt4s1.cloudfront.net</key> 
      <dict> 
        <key>NSExceptionRequiresForwardSecrecy</key> 
          <false/> 
        <key>NSIncludesSubdomains</key> 
          <true/> 
      </dict> 
    </dict> 
  </dict>
  • Update your rollbar.js snippet to use cdn.rollbar.com
    • This will fix iOS 9 webviews but will cause rollbar.js to not work properly for IE6 and IE8 users
  var _rollbarConfig = {
    accessToken: "POST_CLIENT_ITEM_ACCESS_TOKEN",
    // ... other configuration
    rollbarJsUrl: "https://cdn.rollbar.com/js/v1.7/rollbar.min.js"
  };

Next steps

Help / Support

If you run into any issues, please email us at [email protected]

You can also find us in IRC: #rollbar on chat.freenode.net

For bug reports, please open an issue on GitHub.

Developing

To set up a development environment, you'll need Node.js and npm.

  1. git submodule update --init
  2. npm install -D
  3. make

To run the tests, run make test

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature).
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request