Documentation

JavaScript

Documentation - Raygun4JS - JavaScript Error Reporting

Setup instructions

The Raygun4JS provider

Crash reporting and error monitoring with Raygun is available using the Raygun4JS provider. Raygun4JS is a library that you can easily add to your website or web application, which will then allow you to transmit all exceptions to your Raygun.io dashboard. Installation is painless, and configuring your site to transmit errors takes only 5 minutes.

The provider is a single script which includes the sole dependency, allowing you to drop it straight in. It is now also available as a script snippet which loads the library from Raygun's CDN.

The provider is open source and available at Raygun4JS GitHub repository.

How do I send to Raygun?

Raygun4JS has two main functions, the first to transmit exceptions manually caught in try-catch blocks, and the second which is a handler to catch and send all errors caught in window.onerror.

Supported browsers and platforms

Modern browsers are supported out-of-the-box: auto-updating versions of Chrome, Firefox, IE10+, Safari and Opera. IE 8 and 9 are also supported (the former requires the allowInsecureSubmissions option). Pulse requires IE >= 9 for Navigation Timing API support.

Raygun4JS also has dedicated support for WinJS, and is also known to work on various Android browsers and smart TVs. Support for React Native and other bundled mobile frameworks is available.

It is also known to run on old versions of Firefox (pre 4.0) and Opera. Legacy browsers such as Netscape, IE <= 7 et al are supported on a best-effort basis. Naturally, browsers that do not have JavaScript enabled are incompatible.

V1 documentation

 Raygun4JS V1 should only be used by legacy customers or for applications that can't use asynchronous loading, such as mobile apps in webviews (Cordova etc).

Contents

Getting started

Step 1

Add this snippet to your markup, before the closing </head> tag:

<script type="text/javascript">
  !function(a,b,c,d,e,f,g,h){a.RaygunObject=e,a[e]=a[e]||function(){
  (a[e].o=a[e].o||[]).push(arguments)},f=b.createElement(c),g=b.getElementsByTagName(c)[0],
  f.async=1,f.src=d,g.parentNode.insertBefore(f,g),h=a.onerror,a.onerror=function(b,c,d,f,g){
  h&&h(b,c,d,f,g),g||(g=new Error(b)),a[e].q=a[e].q||[],a[e].q.push({
  e:g})}}(window,document,"script","//cdn.raygun.io/raygun4js/raygun.min.js","rg4js");
</script>

This will fetch the raygun4js script from our CDN asynchronously, so it doesn't block the page load. It will also catch errors that are thrown while the page is loading, and send them when the script is ready.

Alternatively, if you do not want errors to be caught while the page is loading, use this snippet instead:

<script type="text/javascript">
  !function(a,b,c,d,e,f,g,h){a.RaygunObject=e,a[e]=a[e]||function(){
  (a[e].o=a[e].o||[]).push(arguments)},g=b.createElement(c),h=b.getElementsByTagName(c)[0],
  g.async=1,g.src=d,a.__raygunNoConflict=!!f,h.parentNode.insertBefore(g,h);
  }(window,document,"script","//cdn.raygun.io/raygun4js/raygun.min.js","rg4js");
</script>

Step 2

Add the following lines to your JS site code just before the closing body tag and paste in your API key (from your Raygun dashboard), to set up the provider to automatically send errors to your Raygun:

<script type="text/javascript">
  rg4js('apiKey', 'paste_your_api_key_here');
  rg4js('enableCrashReporting', true);
</script>

This will configure the provider to send to your Raygun app, and to automatically send all unhandled errors.

That's it for the basic setup! See Usage below for more info on how to send errors.

For mutating the provider after initial setup, you can interact with the global Raygun object after page load. By example with plain jQuery:

$(window).load(function () {
  rg4js('withTags', ['Loaded']);
});

Alternative setup options

Note: This library can now be interacted with in two ways, the V1 API and the V2 API. The V1 API is available as 'public' functions on the global Raygun object, and is intended to be used to control the provider during runtime. Legacy setup methods remain on this API for backwards compatibility with 1.x releases. The V2 API is made available when using the snippet (above), and is used to asynchronously configure the provider during onLoad. This is the recommended approach for new setups.

If you are installing the provider locally using a package manager or manually, you can either use the V2 API by adding the snippet and replace the second-last parameter with the URL of your hosted version of the script, or use the V1 API. The snippet/V2 approach does not support the script being bundled with other vendor scripts, but the V1 API does.

Snippet without page load error handler

If you do not want errors to be caught while the page is loading, use this snippet here.

Synchronous methods

Bower

Using the Bower package manager, you can install it by running this command in a shell:

bower install raygun4js

 

NPM

npm install raygun4js --save

This lets you require the library with tools such as Webpack or Browserify.

 

NuGet

Visual Studio users can get it by opening the Package Manager Console and typing:

Install-Package raygun4js

 

CDN

Raygun4JS can also be loaded directly from our content delivery network:

<script type="text/javascript" src="//cdn.raygun.io/raygun4js/raygun.min.js"></script>

It is available using HTTP or HTTPS.

The most current release is always available in /raygun4js/, while previous releases are available as subdirectories, for instance /raygun4js/1.14.0/raygun.js. The vanilla versions are also available as below.

Note that the CDN's current unversioned release (/raygun4js/raygun.js) may lag behind the package managers by around a week, to ensure stability. When a new version is released, this will be available immediately from its versioned folder as above.

 

React Native/Webpack/as a UMD module

React Native and other bundled app frameworks that uses packaging/module loading libraries can use Raygun4JS as a UMD module:

// Install the library
npm install raygun4js --save

// In a central module (as early as possible), reference and install the library with either this syntax:
import rg4js from 'raygun4js';
// Or this syntax:
var rg4js = require('raygun4js');

// Then set your config options (in one module only)
rg4js('enableCrashReporting', true);
rg4js('apiKey', 'paste_your_api_key_here');

All unhandled errors will then be sent to Raygun. You can then import rg4js from 'raygun4js' in any other modules and use the rest of the V2 API below - including rg4js('send', anErrorObject) for manual error sending.

Note that the UMD module has a major limitation for web applications as errors that occur during page load in the bundle before the Raygun dependency is executed, such as syntax errors or runtime errors, can't be caught and sent. Also, Pulse timings may be severly disrupted. Thus, the HTML snippet at the end of </head> is greatly preferred for to ensure you don't miss any errors and for data correctness. The tradeoff with this method is that it is slightly less idiomatic to call rg4js as a global variable without importing/requiring it. As such, we only recommend this approach for React Native and other bundled mobile app (non-web) frameworks.

 

Manual download

Download the production version or the development version.

You can also download a version without the jQuery hooks if you are not using jQuery or you wish to provide your own hooks. Get this as a production version or development version.

Usage

To send errors manually:

rg4js('apiKey', 'paste_your_api_key_here');

try {
  throw new Error("Description of the error");
} catch (e) {
  rg4js('send', e);
}

In order to get stack traces, you need to wrap your code in a try/catch block like above. Otherwise the error hits window.onerror handler and may only contain the error message, line number, and column number.

You also need to throw errors with throw new Error('foo') instead of throw 'foo'.

To automatically catch and send unhandled errors, you can attach the automatic window.onerror handler callback:

rg4js('enableCrashReporting', true);

If you need to detach it from window.onerror (which will disable automatic unhandled error sending):

rg4js('detach');

IE8

If you are serving your site over HTTP and want IE8 to be able to submit JavaScript errors then you will need to set the following setting which will allow IE8 to submit the error over HTTP. Otherwise the provider will only submit over HTTPS which IE8 will not allow while being served over HTTP.

rg4js('options', {
  allowInsecureSubmissions: true
});

Enabling Pulse

To enable Pulse (Real User Monitoring), make this call:

rg4js('enablePulse', true);

Initialization options

To configure the provider, call one of these and pass in an options object:

rg4js('options', {
  // Add some or all of the options below
});

The second parameter should contain one or more of these keys and a value to customize the behavior:

allowInsecureSubmissions - posts error payloads over HTTP. This allows IE8 to send JS errors.

ignoreAjaxAbort - User-aborted Ajax calls result in errors - if this option is true, these will not be sent.

ignoreAjaxError - Ajax requests that return error codes will not be sent as errors to Raygun if this option is true.

debugMode - Raygun4JS will log to the console when sending errors.

ignore3rdPartyErrors - ignores any errors that have no stack trace information. This will discard any errors that occur completely within 3rd party scripts - if code loaded from the current domain called the 3rd party function, it will have at least one stack line and will still be sent. This option removes nonsense 'Script Error's from your Raygun dashboard.

wrapAsynchronousCallbacks - disables wrapping of async setTimeout/setInterval callbacks when set to false. Defaults to true. This option is respected when attach() is called.

excludedHostnames - Prevents errors from being sent from certain hostnames (domains) by providing an array of strings or RegExp objects (for partial matches). Each should match the hostname or TLD that you want to exclude. Note that protocols are not tested.

excludedUserAgents - Prevents errors from being sent from certain clients, based on their user agent string. Pass in an array of strings or RegExp objects. Useful for ignoring headless browsers in unit testing, or old/problematic clients.

disableAnonymousUserTracking - Prevent user data being sent for anonymous users (those where setUser hasn't been called).

disableErrorTracking - Prevent all errors from being sent.

disablePulse - Prevent Pulse real user monitoring events from being sent.

apiEndpoint - A string URI containing the protocol, domain and port (optional) where all payloads will be sent to. This can be used to proxy payloads to the Raygun API through your own server. When not set this defaults internally to the Raygun API, and for most usages you won't need to set this.

pulseMaxVirtualPageDuration - The maximum time a virtual page can be considered viewed, in milliseconds (defaults to 30 minutes).

pulseIgnoreUrlCasing - Ignore URL casing when sending data to Pulse.

Example:

rg4js('options', {
  allowInsecureSubmissions: true,
  ignoreAjaxAbort: true,
  ignoreAjaxError: true,
  debugMode: true,
  ignore3rdPartyErrors: false,
  wrapAsynchronousCallbacks: true,
  excludedHostnames: ['localhost', '\.dev'],
  excludedUserAgents: ['PhantomJS', 'MSIE'],
  disableErrorTracking: false,
  disablePulse: false,
  pulseMaxVirtualPageDuration: 1800000
  pulseIgnoreUrlCasing: false
});

Pulse API

Tracking Single Page Application view change events

Raygun Pulse supports client-side SPAs through the trackEvent function:

rg4js('trackEvent', {
  type: 'pageView',
  path: '/' + window.location.pathname // Or perhaps window.location.hash
});

When a route or view change is triggered in your SPA, this function should be called with type being pageView and pathset to a string representing the new view or route. Pulse will collect up all timing information that is available and send it to the dashboard. These are then viewable as 'virtual pages'.

The following are a couple of configuration examples that you can use or adapt for your client-side view library/framework. Naturally, if you are using a more full-featured routing system, you should trigger a pageView inside there when the route changes.

jQuery

$(window).hashchange(function() {
  rg4js('trackEvent', {
      type: 'pageView',
      path: '/' + location.hash
  });
});

AngularJS

$scope.$on('$routeChangeSuccess', function () {
  rg4js('trackEvent', {
      type: 'pageView',
      path: '/' + $scope.area
  });
});

Tracking custom timings

You can override the time when Raygun4JS considers your page to be loaded at, as well as send up to 10 custom timings of your choosing, with the Custom Timings capability.

Breadcrumbs API

Configuration options

These can be controlled via the v2 API

rg4js('one-of-the-below-options')

 

disableAutoBreadcrumbs - Disable all the automatic breadcrumb integrations (clicks, requests, console logs and navigation events). This has an inverse enableAutoBreadcrumbs which is the default

disableAutoBreadcrumbsConsole - Disable just automatic breadcrumb creation from console messages

disableAutoBreadcrumbsNavigation - Disable just automatic breadcrumb creation from navigation events

disableAutoBreadcrumbsClicks - Disable just automatic breadcrumb creation from element clicks

disableAutoBreadcrumbsXHR - Disable just automatic breadcrumb creation XMLHttpRequests

Note: All of the above have an inverse enableAutoBreadcrumbs<type> which is the default

setAutoBreadcrumbsXHRIgnoredHosts - This can be set to an array of hosts to not create a breadcrumb for requests/responses to. It can either be a string that an indexOf check against the host is made, or a regex which is matched against the host.

setBreadcrumbLevel - Set the minimum level of breadcrumb to record. This works the same as log levels, you may set it to debug, info, warning and error and it will only keep breadcrumbs with a level equal or above what this is set to. Defaults to info.

logContentsOfXhrCalls - If set to true will include the body contents of XHR request and responses in Breadcrumb metadata, defaults to false

 

Logging a breadcrumb

Breadcrumbs can be manually logged via rg4js('recordBreadcrumb', ...)

There are two argument formats:

1. Message and optional object

rg4js('recordBreadcrumb', 'breadcrumb-message', { object: 'that will be attached to the breadcrumb custom data' })

This is the quickest way to log basic breadcrumbs, requiring only a message and optionally an object to attach some metadata

2. Message, metadata, level, location, class configuration

rg4js('recordBreadcrumb', {message: 'breadcrumb-message', metadata: {goes: 'here'}, level: 'info', location: 'class:method'})

Use the above if you wish to have further control of the breadcrumb and configure the level (debug, info, warning, error) or set the class/method the breadcrumb was logged from.

 

Payload size configuration

To help ensure your payload does not become too large only the most recent 32 breadcrumbs are kept, as well as limiting the size of recorded network request/response texts to 500 characters.

Multiple Raygun objects on a single page

You can have multiple Raygun objects in global scope. This lets you set them up with different API keys for instance, and allow you to send different errors to more than one application in the Raygun web app. To create a new Raygun object and use it call:

var secondRaygun = rg4js('getRaygunInstance').constructNewRaygun();
secondRaygun.init('apikey');
secondRaygun.send(...);

Only one Raygun object can be attached as the window.onerror handler at one time, as onerror can only be bound to one function at once. Whichever Raygun object had attach() called on it last will handle the unhandle errors for the page. Note that you should use the V1 API to send using the second Raygun object, and it should be created and called once the page is loaded (for instance in an onload callback).

NoConflict mode

If you already have an variable called Raygun attached to window, you can prevent the provider from overwriting this by enabling NoConflict mode:

rg4js('noConflict', true);

To then get an instance of the Raygun object, call this once the page is loaded:

var raygun = rg4js('getRaygunInstance');

Callback events

onBeforeSend

rg4js('onBeforeSend', function (payload) {
  return payload;
});

Call this function and pass in a function which takes one parameter (see the example below). This callback function will be called immediately before the payload is sent. The one parameter it gets will be the payload that is about to be sent. Thus from your function you can inspect the payload and decide whether or not to send it.

From the supplied function, you should return either the payload, or return false.

If your function returns a truthy object, Raygun4JS will attempt to send it as supplied. Thus, you can mutate it as per your needs - preferably only the values if you wish to filter out data that is not taken care of by filterSensitiveData(). You can also of course return it as supplied.

If, after inspecting the payload, you wish to discard it and abort the send to Raygun, simply return false. By example:

var myBeforeSend = function (payload) {
  console.log(payload); // Modify the payload here if necessary
  return payload; // Return false here to abort the send
}

rg4js('onBeforeSend', myBeforeSend);

onAfterSend

rg4js('onAfterSend', function (xhrResponse) {
  // Inspect the XHR response here
});

Call this function and pass in a function which takes one parameter (see the example below). This callback function will be immediately called after the XHR request for a Crash Reporting or Pulse event responds successfully, or errors out (its onerror was called). You can inspect the one parameter, which is the XHR object containing the HTTP response data.

onBeforeXHR

rg4js('onBeforeXHR', function (xhr) {
  // Mutate the xhr parameter as per your needs
});

Call this function when you want control over the XmlHttpRequest object that is used to send error payloads to the API. Pass in a callback that receives one parameter (which is the XHR object). Your callback will be called after the XHR object is opened, immediately before it is sent.

For instance, you can use this to add custom HTTP headers.

Custom error grouping

You can control custom grouping for error instances by passing in a callback. This will override the automatic grouping and be used to group error instances together. Errors with the same key will be placed within the same error group.

The callback's signature should take in the error payload, stackTrace and options and return a string, ideally 64 characters or less. 

If the callback returns null or or a non-string the error will be grouped using Raygun's server side grouping logic (this can be useful if you only wish to use custom grouping for a subset of your errors).

var groupingKeyCallback = function (payload, stackTrace, options) {
  // Inspect the above parameters and return a hash derived from the properties you want

  return payload.Details.Error.Message; // Naive message-based grouping only
};

rg4js('groupingKey', groupingKeyCallback);

Sending custom data

The Raygun object has a withCustomData() function where you can pass in JavaScript objects that will be sent with each error that occurs. This allows you to provide any useful data that is global or in scope.

There are two ways to do this:

On initialization

rg4js('withCustomData', { custom: 'data' });

This custom data is set at initialization, and will be present and static on every Error that is sent.

During a send

You can also pass custom data with manual send calls, with an options object. This lets you add variables that are in scope or global when handled in catch blocks. For example:

rg4js('send', {
  error: e,
  customData: [{ foo: 'bar' }];
});

This custom data can contain whatever is in scope when you are sending manually.

customData can be an object or an array:

If an object is passed in the Custom Data tab in the dashboard will display the keys with the values nested below.

If an array is passed in their index will be displayed with the values below.

Either may contain further JavaScript objects, strings, numbers, dates and so on.

Providing custom data with a callback

To send the state of variables at the time an error occurs, you can pass withCustomData a function. This needs to return an object. By example:

var desiredNum = 1;

function getMyData() {
 return { num: desiredNum };
}

rg4js('withCustomData', getMyData);

desiredNum++;

When an error is thrown, the custom data will contain a 'num' key with a value of 2.

getMyData will be called when Raygun4JS is about to send an error, which will construct the custom data. This will be merged with any custom data provided on a Raygun.send() call.

Adding tags

The Raygun dashboard can also display tags for errors. These are arrays of strings or numbers. This is done similar to the above custom data, like so:

On initilization

rg4js('withTags', ['tag1', 'tag2']);

During a Send

rg4js('send', {
  error: e,
  tags: ['tag3'];
});

Adding tags with a callback function

As above for custom data, withTags() can now also accept a callback function. This will be called when the provider is about to send, to construct the tags. The function you pass to withTags() should return an array (ideally of strings/Numbers/Dates).

Affected User tracking

By default, Raygun4JS assigns a unique anonymous ID for the current user. This is stored as a cookie. If the current user changes, to reset it and assign a new ID you can call:

rg4js('getRaygunInstance').resetAnonymousUser();

Disabling anonymous user tracking

rg4js('options', { disableAnonymousUserTracking: true });

Rich user data

You can provide data about the currently logged in user to Raygun by calling:

rg4js('setUser', {
  identifier: 'user_email_address@localhost.local',
  isAnonymous: false,
  email: 'emailaddress@localhost.local',
  firstName: 'Foo',
  fullName: 'Foo Bar',
  uuid: 'BAE62917-ACE8-ab3D-9287-B6A33B8E8C55'
});

Only identifier or the first parameter is required. This method takes additional parameters that are used when reporting over the affected users. the full method signature is:

setUser: function (user, isAnonymous, email, fullName, firstName, uuid)

user is the user identifier. This will be used to uniquely identify the user within Raygun. This is the only required parameter, but is only required if you are using user tracking.

isAnonymous is a bool indicating whether the user is anonymous or actually has a user account. Even if this is set to true, you should still give the user a unique identifier of some kind.

email is the user's email address.

fullName is the user's full name.

firstName is the user's first or preferred name.

uuid is the identifier of the device the app is running on. This could be used to correlate user accounts over multiple machines.

This will be transmitted with each message. A count of unique users will appear on the dashboard in the individual error view. If you provide an email address, the user's Gravatar will be displayed (if they have one). This method is optional; if it is not called no user tracking will be performed. Note that if the user context changes (such as in an SPA), you should call this method again to update it.

Resetting the user

You can now pass in empty strings (or false to isAnonymous) to reset the current user for login/logout scenarios.

Anonymous user tracking

By default, Raygun4JS assigns a unique anonymous ID for the current user. This is stored as a cookie. If the current user changes, to reset it and assign a new ID you can call:

Raygun.resetAnonymousUser();

Disabling anonymous user tracking

rg4js('options', { disableAnonymousUserTracking: true });

Version filtering

You can set a version for your app by calling:

rg4js('setVersion', '1.0.0.0');

This will allow you to filter the errors in the dashboard by that version. You can also select only the latest version, to ignore errors that were triggered by ancient versions of your code. The parameter should be a string in the format x.x.x if you want to get the version sorting in Raygun to work nicely, where x is a non-negative integer.

Filtering sensitive data

You can blacklist keys to prevent their values from being sent it the payload by providing an array of key names:

rg4js('filterSensitiveData', ['password', 'credit_card']);

If any key matches one in the input array, its value will be replaced with [removed by filter].

You can also pass RegExp objects in the array to filterSensitiveData, for controllable matching of keys:

var creditCardDataRegex = /credit\D*/; // Remove any keys that begin with 'credit'

rg4js('filterSensitiveData', [creditCardDataRegex]);

Change filter scope

By default this is applied to the UserCustomData object only (legacy behavior). To apply this to any key-value pair, you can change the filtering scope:

rg4js('setFilterScope', 'all'); // Filter any key in the payload
rg4js('setFilterScope', 'customData'); // Just filter the custom data (default)

You can also pass RegExp objects in the array to filterSensitiveData, for controllable matching of keys:

var creditCardDataRegex = /credit\D*/; // Remove any keys that begin with 'credit'

rg4js('filterSensitiveData', [creditCardDataRegex]);

Source maps

Raygun4JS features source maps support through the transmission of column numbers for errors, where available. This is confirmed to work in recent version of Chrome, Safari and Opera, and IE 10 and 11. See the source maps documentation to the left for more information.

rg4js('options', {
  allowInsecureSubmissions: true
});

Offline saving

The provider has a feature where if errors are caught when there is no network activity they can be saved (in Local Storage). When an error arrives and connectivity is regained, previously saved errors are then sent. This is useful in environments like WinJS, where a mobile device's internet connection is not constant.

Offline saving is disabled by default. To get or set this option, call the following after your init() call:

rg4js('saveIfOffline', true);

If an error is caught and no network connectivity is available (the Raygun API cannot be reached), or if the request times out after 10s, the error will be saved to LocalStorage. This is confirmed to work on Chrome, Firefox, IE10/11, Opera and WinJS.

Limited support is available for IE 8 and 9 - errors will only be saved if the request times out.

Errors in scripts hosted on other domains

Browsers have varying behavior for errors that occur in scripts located on domains that are not the origin. Many of these will be listed in Raygun as 'Script Error', or will contain junk stack traces. You can filter out these errors with the following code snippet. There is also an option to whitelist domains which you do want to allow transmission of errors to Raygun, which accepts the domains as an array of strings:

rg4js('options', { ignore3rdPartyErrors: true });

Whitelisting Domains

There is also an option to whitelist domains which you do want to allow transmission of errors to Raygun, which accepts the domains as an array of strings:

rg4js('options', { ignore3rdPartyErrors: true });
rg4js('whitelistCrossOriginDomains', ['code.jquery.com']);

This can be used to allow errors from remote sites and CDNs.

The provider will default to attempt to send errors from subdomains - for instance if the page is loaded from foo.com, and a script is loaded from cdn.foo.com, that error will be transmitted on a best-effort basis.

To get full stack traces from cross-origin domains or subdomains, these requirements should be met:

  • The remote domain should have Access-Control-Allow-Origin set (to include the domain where raygun4js is loaded from).

  • For Chrome the script tag must also have crossOrigin="Anonymous" set.

  • Recent versions of Firefox (>= 31) will transmit errors from remote domains will full stack traces if the header is set (crossOrigin on script tag not needed).

In Chrome, if the origin script tag and remote domain do not meet these requirements the cross-origin error will not be sent.

Other browsers may send on a best-effort basis (version dependent) if some data is available but potentially without a useful stacktrace. The provider will cancel the send if no data is available.

Browser behaviour

Depending on what browser your users are running, the above properties may or may not have an effect. This sums up the situation as of writing:

  • Chrome 30+
  • Firefox 13+
  • Opera 12.50+
  • Safari (at least 6+)

In these browsers, if the script attribute is present, the HTTP header will need to be also present, otherwise the script will be blocked.

Firefox has additional behavior for RuntimeErrors. These will be provided to window.onerror regardless of the two properties, as these aren’t considered a security risk. SyntaxErrors, however, will be blocked in both Gecko and WebKit browsers, if crossorigin is present but the associated cross-origin domain lacks the header.

  • Internet Explorer <= 10

Errors will be reported with all available data in IE 10 and below.

  • Internet Explorer 11+

Third-party errors will not contain any data, and the attributes are not respected at current time.

Limitations of stack trace data

Due to browser API and security limitations, in cases where the message is 'Script error', only one stack trace frame may be present. In this scenario, the line number may not reflect the actual position where the original error was thrown.

For more information, check out this blog post on CORS requirements for Script Errors here.

AngularJS

You can hook failed Ajax requests with $http in AngularJS by providing an Interceptor that sends to Raygun on error. One possible simple implementation, using custom data:

$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  return {
   'requestError': function(rejection) {
       rg4js('send', {
         error: 'Failed $http request',
         customData: { rejection: rejection }
       });
    },

    'responseError': function(rejection) {
       rg4js('send', {
         error: 'Failed $http response',
         customData: { rejection: rejection }
       });
    }
  };
});

For more information, see the official docs under Interceptors.

Vue.js

You can use the Vue.js error handler to send errors directly to Raygun.

Vue.config.errorHandler = function (err, vm, info) {
  rg4js('send', {
    error: err, 
    customData: [{ info: info }]
  });
}

React Native

Firstly, add the library to your project:

npm install --save raygun4js

Then in a central component (e.g index.ios.js/index.android.js), import the library:

import rg4js from 'raygun4js';

Next, configure the provider using your Raygun application's API key. These lines should be called once only early on when your app boots, for example:

export default class YourReactNativeProject extends Component {
  constructor() {
    super()

    rg4js('enableCrashReporting', true);
    rg4js('apiKey', 'add_your_api_key_here');

    // Put any other rg4js() options you want to set here

    rg4js('boot'); // This call must be made last to start the provider
  }
}

Naturally, you can factor the above logic out into a function or separate component, which should be called early on from your main app component.

Finally, see Source Maps below for how to get your minified JS errors mapped back to human-readable stacktraces.

Affected user tracking

You can optionally configure user tracking, either anonymously or non-anonymously (if your app has the concept of a logged-in user and their data available). Here's an example of how to set it up:

constructor() {
    super()

    rg4js('enableCrashReporting', true);
    rg4js('apiKey', 'paste_your_api_key_here');

    this.setupUser();
  }

  setupUser() {
    try {
      var user;
      AsyncStorage.getItem('@raygun:user', (err, result) => {
        if (!result) {
          // One approach is to load the user data from AsyncStorage or the network using fetch(). When that data returns, place the following in its callback:

          user = {
            identifier: 'user@example.com', // A unique ID or email address, or a random ID such as a UUID
            isAnonymous: false, // Or true
            email: 'user@example.com', // Optional
            firstName: 'Foo', // Optional
            fullName: 'Foo Bar', // Optional
            uuid: 'BAE62917-ACE8-ab3D-9287-B6A33B8E8C55' // Optional device identifier
          };

          AsyncStorage.setItem('@raygun:user', JSON.stringify(user), () => { });
        } else {
          user = result;
        }
        
        rg4js('setUser', JSON.parse(user));
        rg4js('boot'); // Ensure this is called finally
      });

    } catch (e) {
    }
  }

Manual error sending

You can manually send an error that you handle in a catch block in a component, by importing 'rg4js' and calling send. The provider should have already been imported and configured (as above) before the code below is called.

import rg4js from 'raygun4js';

export default class YourChildComponent extends Component {

  constructor() {
    try {
      // Bug goes here
    } catch (e) {
      rg4js('send', e);
    }
  }
}

Source maps

For iOS:

Run this command from your project's root directory to build your app JS bundle with source maps:

react-native bundle --platform ios --dev false --entry-file index.ios.js --bundle-output iOS/main.jsbundle --assets-dest ./ios --sourcemap-output ./iOS/main.jsbundle.min.js.map

Then run this command to upload the sourcemap to Raygun:

curl \
-X POST \
-u "emailaddress:password" \
-F "url=file://reactnative.local/main.jsbundle" \
-F "file=@./ios/main.jsbundle.min.js.map" \
https://app.raygun.io/upload/jssymbols/your_application_id

You will need to update the emailaddress and password to a valid Raygun account. If you don't want to use your account credentials you can create a new account and add it to the Owners team, or a team that has access to the Raygun application.

You will also need to replace your_application_id above with the 6-letter application ID code (available at https://app.raygun.com/dashboard/[app_id]).

When errors are received by Raygun, they will then be source mapped to the unminified code automatically. Every time you finish a version of your app and are about to release it, you should run the above two commands to upload the new source map to Raygun. We do note that this process is quite manual, and is expected to be replaced with an automatic first-class workflow for the production release.

For Android:

1. Optional one-time setup action: ensure there is a directory within your project for the JS bundle, e.g mkdir android/app/src/main/assets

2. Run this command from your project's root directory to build your production app bundle with source maps:

react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/main.jsbundle --assets-dest android/app/src/main/res --sourcemap-output android/app/src/main/assets/main.jsbundle.min.js.map

3. Finally, run this command to upload your source map (replacing username, password and your_application_id):

curl \
-X POST \
-u "emailaddress:password" \
-F "url=file://reactnative.local/main.jsbundle" \
-F "file=@./android/app/src/main/assets/main.jsbundle.min.js.map" \
https://app.raygun.io/upload/jssymbols/your_application_id

Note that if you have placed or want to place your jsbundle file in a different location, you can set this location as the value for --sourcemap-output in step 2 and the file=@./ value in the step 3 cURL command.

JavaScript V1

Documentation - Raygun4JS V1 - JavaScript Error Reporting

The following documentation is for Raygun4js V1 only. Raygun4js V1 should only be used by legacy customers or for applications that can't use asynchronous loading, such as mobile apps in webviews (Cordova etc).

Go to V2 documentation

Contents

Getting started

Step 1

Load Raygun4JS directly from Raygun's content delivery network:

<script src="path/to/raygun.min.js" type="text/javascript"></script>

It is available using HTTP or HTTPS.

The most current release is always available in /raygun4js/, while previous releases are available as subdirectories, for instance /raygun4js/1.14.0/raygun.js. The vanilla versions are also available as below.

Note that the CDN's current unversioned release (/raygun4js/raygun.js) may lag behind the package managers by around a week, to ensure stability. When a new version is released, this will be available immediately from its versioned folder as above.

Step 2

Add the following lines to your JS site code just before the closing body tag and paste in your API key (from your Raygun dashboard), to set up the provider to automatically send errors to your Raygun:

<script type="text/javascript">
  Raygun.init('yourApiKey', { 
    // Setup options here - see Initialization Options below
  });
  Raygun.attach();
</script>

This will configure the provider to send to your Raygun app, and to automatically send all unhandled errors.

That's it for the basic setup! See Usage below for more info on how to send errors.

For mutating the provider after initial setup, you can interact with the global Raygun object after page load. By example with plain jQuery:

$(window).load(function () {
  Raygun.withTags(["Loaded"]);
});

Alternative setup options

The Raygun4JS library can be interacted with in two ways - the V1 API and the V2 API. The V1 API is available as 'public' functions on the global Raygun object, and is intended to be used to control the provider during runtime. Legacy setup methods remain on the V1 API for backwards compatibility with 1.x releases. The V2 API is made available when using a snippet, and is used to asynchronously configure the provider during onLoad. This is the recommended approach for new setups.

If you are installing the provider locally using a package manager or manually, you can either use the V2 API by adding the snippet and replace the second-last parameter with the URL of your hosted version of the script, or use the V1 API. The snippet/V2 approach does not support the script being bundled with other vendor scripts, but the V1 API does.

Synchronous methods

Bower

Using the Bower package manager, you can install it by running this command in a shell:

bower install raygun4js

 

NPM

npm install raygun4js --save

This lets you require the library with tools such as Webpack or Browserify.

 

NuGet

Visual Studio users can get it by opening the Package Manager Console and typing:

Install-Package raygun4js

 

Manual download

Download the production version or the development version. You can also download a version without the jQuery hooks if you are not using jQuery or you wish to provide your own hooks. Get this as a production version or development version.

Usage

To send errors manually:

Raygun.init("apikey");

try {
  throw new Error("Description of the error");
} catch (e) {
  Raygun.send(e)
}

In order to get stack traces, you need to wrap your code in a try/catch block like above. Otherwise the error hits window.onerror handler and may only contain the error message, line number, and column number.

You also need to throw errors with throw new Error('foo') instead of throw 'foo'.

To automatically catch and send unhandled errors, you can attach the automatic window.onerror handler callback:

Raygun.attach();

If you need to detach it from window.onerror (which will disable automatic unhandled error sending):

Raygun.detach();

IE8

If you are serving your site over HTTP and want IE8 to be able to submit JavaScript errors then you will need to set the following setting which will allow IE8 to submit the error over HTTP. Otherwise the provider will only submit over HTTPS which IE8 will not allow while being served over HTTP.

Raygun.init('yourApiKey', { allowInsecureSubmissions: true });

Enabling Pulse

To enable Pulse (Real User Monitoring), make this call:

Raygun.init('apikey', {
  disablePulse: false,
}).attach();

Differences between Raygun4JS V1 and V2

This provider supports two APIs for interacting with the provider, V1 and V2. For initial setup, all functions are interchangeable and available using either method. The public functions available on the global Raygun object can be accessed by calling Raygun.functionName(value) or rg4js(functionName, value) (with the exception of send()).

V1

V1 remains unchanged from previous versions, and all current code is backwards compatible. This API is of the form where functions can be called on the global Raygun object, for instance Raygun.init('your_apikey').attach().

The V1 API is available as 'public' functions on the global Raygun object, and is intended to be used to control the provider during runtime.

V1 supports the script being bundled with other vendor scripts, and V2 does not.

V2

V2 lets you asynchronously configure the provider during onLoad. A new global function is made available, rg4js() (configurable), which accepts parameters that are applied to the provider once it is download asynchronously. This API is of the form rg4js('init', 'your_apikey'). This is the recommended approach for new setups.

Using the snippet to fetch the script from the CDN, along with the V2 API, is superior as errors that occur while the page is loading but Raygun4JS hasn't been downloaded will now be caught. With any of the synchronous methods these will not be sent to Raygun, and the script load will block the page load. Thus, you should use the snippet, the CDN and the V2 API for the best experience for your users.

If you are installing the provider locally using a package manager or manually, you can either use the V2 API by adding the snippet and replace the second-last parameter with the URL of your hosted version of the script.

Initialization options

To configure the provider, call one of these and pass in an options object:

Raygun.init('your_apikey', {
  // Add some or all of the options below
});

The second parameter should contain one or more of these keys and a value to customize the behavior:

allowInsecureSubmissions - posts error payloads over HTTP. This allows IE8 to send JS errors.

ignoreAjaxAbort - User-aborted Ajax calls result in errors - if this option is true, these will not be sent.

ignoreAjaxError - Ajax requests that return error codes will not be sent as errors to Raygun if this option is true.

debugMode - Raygun4JS will log to the console when sending errors.

ignore3rdPartyErrors - ignores any errors that have no stack trace information. This will discard any errors that occur completely within 3rd party scripts - if code loaded from the current domain called the 3rd party function, it will have at least one stack line and will still be sent. This option removes nonsense 'Script Error's from your Raygun dashboard.

wrapAsynchronousCallbacks - disables wrapping of async setTimeout/setInterval callbacks when set to false. Defaults to true. This option is respected when attach() is called.

excludedHostnames - Prevents errors from being sent from certain hostnames (domains) by providing an array of strings or RegExp objects (for partial matches). Each should match the hostname or TLD that you want to exclude. Note that protocols are not tested.

excludedUserAgents - Prevents errors from being sent from certain clients, based on their user agent string. Pass in an array of strings or RegExp objects. Useful for ignoring headless browsers in unit testing, or old/problematic clients.

disableAnonymousUserTracking - Prevent user data being sent for anonymous users (those where setUser hasn't been called).

disableErrorTracking - Prevent all errors from being sent.

disablePulse - Prevent Pulse real user monitoring events from being sent.

apiEndpoint - A string URI containing the protocol, domain and port (optional) where all payloads will be sent to. This can be used to proxy payloads to the Raygun API through your own server. When not set this defaults internally to the Raygun API, and for most usages you won't need to set this.

pulseMaxVirtualPageDuration - The maximum time a virtual page can be considered viewed, in milliseconds (defaults to 30 minutes).

pulseIgnoreUrlCasing - Ignore URL casing when sending data to Pulse.

An example:

Raygun.init('apikey', {
  allowInsecureSubmissions: true,
  ignoreAjaxAbort: true,
  ignoreAjaxError: true,
  debugMode: true,
  ignore3rdPartyErrors: false,
  wrapAsynchronousCallbacks: true,
  excludedHostnames: ['localhost', '\.dev'],
  excludedUserAgents: ['PhantomJS', 'MSIE'],
  disableErrorTracking: false,
  disablePulse: false,
  pulseMaxVirtualPageDuration: 1800000
  pulseIgnoreUrlCasing: false
}).attach(); //This enables Crash Reporting by attaching the automatic window.onerror handler callback

Pulse API

Tracking Single Page Application view change events

Raygun Pulse supports client-side SPAs through the trackEvent function:

Raygun.trackEvent('pageView', { path: '/' + foo });

When a route or view change is triggered in your SPA, this function should be called with type being pageView and pathset to a string representing the new view or route. Pulse will collect up all timing information that is available and send it to the dashboard. These are then viewable as 'virtual pages'.

The following are a couple of configuration examples that you can use or adapt for your client-side view library/framework. Naturally, if you are using a more full-featured routing system, you should trigger a pageView inside there when the route changes.

jQuery

$(window).hashchange(function() {
  Raygun.trackEvent('pageView', {
    path: '/' + location.hash
  });
});

AngularJS

app.run([‘$rootScope’, ‘$window’, ‘$location’, trackPageView]);

function trackPageView($rootScope, $window, $location){
  // watch for successful state transitions
  $rootScope.$on(‘$locationChangeSuccess’, function (event, current) {
    $window.Raygun.trackEvent(‘pageView’, {
      path: $location.url()
    });
  });
}

Multiple Raygun objects on a single page

You can have multiple Raygun objects in global scope. This lets you set them up with different API keys for instance, and allow you to send different errors to more than one application in the Raygun web app. To create a new Raygun object and use it call:

var secondRaygun = Raygun.constructNewRaygun();
secondRaygun.init('apikey');
secondRaygun.send(...)

Only one Raygun object can be attached as the window.onerror handler at one time, as onerror can only be bound to one function at once. Whichever Raygun object had attach() called on it last will handle the unhandle errors for the page. Note that you should use the V1 API to send using the second Raygun object, and it should be created and called once the page is loaded (for instance in an onload callback).

NoConflict mode

If you already have an variable called Raygun attached to window, you can prevent the provider from overwriting this by enabling NoConflict mode:

Raygun.noConflict();

Callback events

onBeforeSend

Raygun.onBeforeSend(function (payload) {
  return payload;
});

Call this function and pass in a function which takes one parameter (see the example below). This callback function will be called immediately before the payload is sent. The one parameter it gets will be the payload that is about to be sent. Thus from your function you can inspect the payload and decide whether or not to send it.

From the supplied function, you should return either the payload, or return false.

If your function returns a truthy object, Raygun4JS will attempt to send it as supplied. Thus, you can mutate it as per your needs - preferably only the values if you wish to filter out data that is not taken care of by filterSensitiveData(). You can also of course return it as supplied.

If, after inspecting the payload, you wish to discard it and abort the send to Raygun, simply return false. By example:

var myBeforeSend = function (payload) {
  console.log(payload); // Modify the payload here if necessary
  return payload; // Return false here to abort the send
}

Raygun.onBeforeSend(myBeforeSend);

onAfterSend

Raygun.onAfterSend(function (xhrResponse) {
  // Inspect the XHR response here
});

Call this function and pass in a function which takes one parameter (see the example below). This callback function will be immediately called after the XHR request for a Crash Reporting or Pulse event responds successfully, or errors out (its onerror was called). You can inspect the one parameter, which is the XHR object containing the HTTP response data.

onBeforeXHR

Raygun.onBeforeXHR(function (xhr) {
  // Mutate the xhr parameter as per your needs
});

Call this function when you want control over the XmlHttpRequest object that is used to send error payloads to the API. Pass in a callback that receives one parameter (which is the XHR object). Your callback will be called after the XHR object is opened, immediately before it is sent.

For instance, you can use this to add custom HTTP headers.

Custom error grouping

You can control custom grouping for error instances by passing in a callback. This will override the automatic grouping and be used to group error instances together. Errors with the same key will be placed within the same error group. The callback's signature should take in the error payload, stackTrace and options and return a string, ideally 64 characters or less. If the callback returns null or or a non-string the error will be grouped using Raygun's server side grouping logic (this can be useful if you only wish to use custom grouping for a subset of your errors).

var groupingKeyCallback = function (payload, stackTrace, options) {
  // Inspect the above parameters and return a hash derived from the properties you want

  return payload.Details.Error.Message; // Naive message-based grouping only
};


Raygun.groupingKey(groupingKeyCallback);

Sending custom data

The Raygun object has a withCustomData() function where you can pass in JavaScript objects that will be sent with each error that occurs. This allows you to provide any useful data that is global or in scope.

There are two ways to do this:

On initialization

Raygun.withCustomData({ custom: 'data' });

This custom data is set at initialization, and will be present and static on every Error that is sent.

During a send

You can also pass custom data with manual send calls, with an options object. This lets you add variables that are in scope or global when handled in catch blocks. For example:

Raygun.send(err, customData)

This custom data can contain whatever is in scope when you are sending manually.

customData can be an object or an array:

If an object is passed in the Custom Data tab in the dashboard will display the keys with the values nested below.

If an array is passed in their index will be displayed with the values below.

Either may contain further JavaScript objects, strings, numbers, dates and so on.

Providing custom data with a callback

To send the state of variables at the time an error occurs, you can pass withCustomData a function. This needs to return an object. By example:

var desiredNum = 1;

function getMyData() {
 return { num: desiredNum };
}

Raygun.init('apikey').attach().withCustomData(getMyData);

desiredNum++;

When an error is thrown, the custom data will contain a 'num' key with a value of 2.

getMyData will be called when Raygun4JS is about to send an error, which will construct the custom data. This will be merged with any custom data provided on a Raygun.send() call.

Adding tags

The Raygun dashboard can also display tags for errors. These are arrays of strings or Numbers. This is done similar to the above custom data, like so:

On initilization

Raygun.init('apikey').withTags(array)

Or

Raygun.withTags(['tag1', 'tag2'])

During a Send

Pass tags in as the third parameter:

Raygun.send(err, [{ foo: 'bar' }]);

Adding tags with a callback function

As above for custom data, withTags() can now also accept a callback function. This will be called when the provider is about to send, to construct the tags. The function you pass to withTags() should return an array (ideally of strings/Numbers/Dates).

Affected User tracking

By default, Raygun4JS assigns a unique anonymous ID for the current user. This is stored as a cookie. If the current user changes, to reset it and assign a new ID you can call:

Raygun.resetAnonymousUser();

Disabling anonymous user tracking

Raygun.init('apikey', { disableAnonymousUserTracking: true });

Rich user data

You can provide data about the currently logged in user to Raygun by calling:

Raygun.setUser(
  'user_email_address@localhost.local', // identifier
  false, // isAnonymous
  'user_email_address@localhost.local', // email
  'Foo Bar', // fullName
  'Foo', // firstName
  'BAE62917-ACE8-ab3D-9287-B6A33B8E8C55' // uuid
);

Only identifier or the first parameter is required. This method takes additional parameters that are used when reporting over the affected users. the full method signature is:

setUser: function (user, isAnonymous, email, fullName, firstName, uuid)

user is the user identifier. This will be used to uniquely identify the user within Raygun. This is the only required parameter, but is only required if you are using user tracking.

isAnonymous is a bool indicating whether the user is anonymous or actually has a user account. Even if this is set to true, you should still give the user a unique identifier of some kind.

email is the user's email address.

fullName is the user's full name.

firstName is the user's first or preferred name.

uuid is the identifier of the device the app is running on. This could be used to correlate user accounts over multiple machines.

This will be transmitted with each message. A count of unique users will appear on the dashboard in the individual error view. If you provide an email address, the user's Gravatar will be displayed (if they have one). This method is optional; if it is not called no user tracking will be performed. Note that if the user context changes (such as in an SPA), you should call this method again to update it.

Resetting the user

You can now pass in empty strings (or false to isAnonymous) to reset the current user for login/logout scenarios.

Version filtering

You can set a version for your app by calling:

Raygun.setVersion('1.0.0.0');

This will allow you to filter the errors in the dashboard by that version. You can also select only the latest version, to ignore errors that were triggered by ancient versions of your code. The parameter should be a string in the format x.x.x if you want to get the version sorting in Raygun to work nicely, where x is a non-negative integer.

Filtering sensitive data

You can blacklist keys to prevent their values from being sent it the payload by providing an array of key names:

Raygun.filterSensitiveData(['password', 'credit_card']);

If any key matches one in the input array, its value will be replaced with [removed by filter].

You can also pass RegExp objects in the array to filterSensitiveData, for controllable matching of keys:

var creditCardDataRegex = /credit\D*/; // Remove any keys that begin with 'credit'

Raygun.filterSensitiveData([creditCardDataRegex]);

Change filter scope

By default this is applied to the UserCustomData object only (legacy behavior). To apply this to any key-value pair, you can change the filtering scope:

Raygun.setFilterScope('all');

You can also pass RegExp objects in the array to filterSensitiveData, for controllable matching of keys:

var creditCardDataRegex = /credit\D*/; // Remove any keys that begin with 'credit'

Raygun.filterSensitiveData([creditCardDataRegex]);

Source maps

Raygun4JS features source maps support through the transmission of column numbers for errors, where available. This is confirmed to work in recent version of Chrome, Safari and Opera, and IE 10 and 11. See the source maps documentation to the left for more information.

Raygun.init('yourApiKey', { allowInsecureSubmissions: true });

Offline saving

The provider has a feature where if errors are caught when there is no network activity they can be saved (in Local Storage). When an error arrives and connectivity is regained, previously saved errors are then sent. This is useful in environments like WinJS, where a mobile device's internet connection is not constant.

Offline saving is disabled by default. To get or set this option, call the following after your init() call:

Raygun.saveIfOffline(true);

If an error is caught and no network connectivity is available (the Raygun API cannot be reached), or if the request times out after 10s, the error will be saved to LocalStorage. This is confirmed to work on Chrome, Firefox, IE10/11, Opera and WinJS.

Limited support is available for IE 8 and 9 - errors will only be saved if the request times out.

Errors in scripts hosted on other domains

Browsers have varying behavior for errors that occur in scripts located on domains that are not the origin. Many of these will be listed in Raygun as 'Script Error', or will contain junk stack traces. You can filter out these errors with the following code snippet. There is also an option to whitelist domains which you do want to allow transmission of errors to Raygun, which accepts the domains as an array of strings:

Raygun.init('apikey', { ignore3rdPartyErrors: true });

Whitelisting Domains

There is also an option to whitelist domains which you do want to allow transmission of errors to Raygun, which accepts the domains as an array of strings:

Raygun.init('apikey', { ignore3rdPartyErrors: true }).whitelistCrossOriginDomains(['code.jquery.com']);

This can be used to allow errors from remote sites and CDNs.

The provider will default to attempt to send errors from subdomains - for instance if the page is loaded from foo.com, and a script is loaded from cdn.foo.com, that error will be transmitted on a best-effort basis.

To get full stack traces from cross-origin domains or subdomains, these requirements should be met:

  • The remote domain should have Access-Control-Allow-Origin set (to include the domain where raygun4js is loaded from).

  • For Chrome the script tag must also have crossOrigin="Anonymous" set.

  • Recent versions of Firefox (>= 31) will transmit errors from remote domains will full stack traces if the header is set (crossOrigin on script tag not needed).

In Chrome, if the origin script tag and remote domain do not meet these requirements the cross-origin error will not be sent.

Other browsers may send on a best-effort basis (version dependent) if some data is available but potentially without a useful stacktrace. The provider will cancel the send if no data is available.

Browser behaviour

Depending on what browser your users are running, the above properties may or may not have an effect. This sums up the situation as of writing:

  • Chrome 30+
  • Firefox 13+
  • Opera 12.50+
  • Safari (at least 6+)

In these browsers, if the script attribute is present, the HTTP header will need to be also present, otherwise the script will be blocked.

Firefox has additional behavior for RuntimeErrors. These will be provided to window.onerror regardless of the two properties, as these aren’t considered a security risk. SyntaxErrors, however, will be blocked in both Gecko and WebKit browsers, if crossorigin is present but the associated cross-origin domain lacks the header.

  • Internet Explorer <= 10

Errors will be reported with all available data in IE 10 and below.

  • Internet Explorer 11+

Third-party errors will not contain any data, and the attributes are not respected at current time.

Limitations of stack trace data

Due to browser API and security limitations, in cases where the message is 'Script error', only one stack trace frame may be present. In this scenario, the line number may not reflect the actual position where the original error was thrown.

For more information, check out this blog post on CORS requirements for Script Errors here.

AngularJS

You can hook failed Ajax requests with $http in AngularJS by providing an Interceptor that sends to Raygun on error. One possible simple implementation, using custom data:

$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  return {
   'requestError': function(rejection) {
       Raygun.send(new Error('Failed $http request'), { rejection: rejection });
    },

    'responseError': function(rejection) {
       Raygun.send(new Error('Failed $http response'), { rejection: rejection });
    }
  };
});

For more information, see the official docs under Interceptors.

Documentation missing?

If we don't have documentation about your desired topic, send us a message and we'll create it for you.