Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

raygun4js

MindscapeHQ109.9kSEE LICENSE IN https://github.com/MindscapeHQ/raygun4js/blob/master/LICENSE3.1.3TypeScript support: included

Raygun.com plugin for JavaScript

error, tracking, raygun, clientside

readme

Raygun4js

Raygun.com provider for client-side JavaScript

Getting Started

Step 1

No installation via a package manager is required. Just add the following snippet to the beginning of the <head> tag within your markup. Please include this snippet before any other <script> tag references are made to ensure that Raygun has the best chance to capture all error events on the page.

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

The above snippet will fetch the Raygun4JS script from our CDN asynchronously, so it doesn't block other scripts from being loaded. It will also catch errors that are thrown while the page is loading, and send them when the script is ready.

Note: If you encounter a situation where no events are appearing within Raygun, you may need to hard code the URL protocol so that the CDN matches your hosting environment. This could look like one of the following -

  • https://cdn.raygun.io/raygun4js/raygun.min.js
  • http://cdn.raygun.io/raygun4js/raygun.min.js

This will be in replacement of //cdn.raygun.io/raygun4js/raygun.min.js.

Via package manager installation

For installations and usage via a package manager, refer to the Synchronous methods section of this document.

Step 2

Add the following lines to your JS site code and paste in your API key (from your Raygun Application Settings), to set up the provider to automatically send errors to your Raygun app:

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

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

Note that using these methods will not catch errors thrown while the page is loading. The script needs to be referenced before your other site/app scripts and will block the page load while it is being downloaded/parsed/executed.

This will also disrupt RUM timings, making them erroneous. For RUM, it is especially important that the async snippet method above is used, instead of one of the following.

With Bower

Run bower install raygun4js

With NPM

npm install raygun4js --save

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

From NuGet

Visual Studio users can get it by opening the Package Manager Console and typing Install-Package raygun4js

React Native/as a UMD module

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

// Install the library

npm install raygun4js --save

// In a central module, reference and install the library

import rg4js from 'raygun4js'; // Import the library with this syntax
var rg4js = require('raygun4js'); // Or this syntax

rg4js('enableCrashReporting', true);
rg4js('apiKey', 'paste_your_api_key_here');
// Any other config options you want such as rg4js('setUser', ...) [see below]
rg4js('boot'); // For React Native only: add this after all other config options have been called

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

If you use this approach, we appreciate your feedback as this is a new feature for the library.

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

If you are using the CDN, be sure to call these usage methods after the installation.

To send errors manually:

try {
  throw new Error('oops');
}
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 (this will disable automatic unhandled error sending):

rg4js('detach');

Documentation

Initialization Options

To configure the provider, call this 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:

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 options is true.

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

wrapAsynchronousCallbacks - if set to false, async callback functions triggered by setTimeout/setInterval will not be wrapped when attach() is called. Defaults to true

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. Errors that occur in browser extensions or that have been triggered by bots/crawlers that appear to come from your website will also be ignored. Note: IE 9 and below have no stacktrace information and errors will be discarded with this enabled.

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 user agents by providing an array of strings. This is very helpful to exclude errors reported by certain browsers or test automation with CasperJS, PhantomJS or any other testing utility that sends a custom user agent. If a part of the client's navigator.userAgent matches one of the given strings in the array, then the client will be excluded from error reporting.

disableErrorTracking - Stops all errors from being sent to Raygun. This includes errors automatically picked up by global error handlers as well as errors manually sent.

disablePulse - Stops 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.

clientIp - A string containing the client's IP address. RUM requests will be associated to this IP address when set. Particularly useful when proxying payloads to the Raygun API using the apiEndpoint option and maintaining RUM's geographic lookup feature.

Note: navigator.sendBeacon is used to send RUM payloads when a page is unloading. As such the clientIp feature will not associate this last payload.

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

captureUnhandledRejections - Automatically catch send errors relating to unhandled promise rejections. See MDN for browser support.

setCookieAsSecure - If the cookies are being used (only used on browsers which don't support localStorage or sessionStorage) then they will be created using the ; secure flag and thus cookies only work on HTTPS.

captureMissingRequests - RUM uses the window.performance API to track XHR timing information and (depending on the browser) not all non-2XX XHR timings are recorded by this API. This option enables the tracking of these missing XHR's calls by tracking the difference between send & success XHR handlers. This is not enabled by default due these timings being as accurate as the performance API.

automaticPerformanceCustomTimings - When enabled Raygun4JS will track each window.performance.measure call as a custom timing entry. This enables developers to use a more native API for tracking performance timings. More information about performance.measure can be found on MDN.

trackCoreWebVitals - When enabled, Raygun4JS will automatically track and report Core Web Vitals. This is enabled by default.

trackViewportDimensions - When enabled, Raygun4JS will send the browser's viewport dimensions with each RUM session payload. This is enabled by default.

An example raygun4js configuration:

rg4js('options', {
  ignoreAjaxAbort: true,
  ignoreAjaxError: true,
  debugMode: true,
  ignore3rdPartyErrors: false,
  wrapAsynchronousCallbacks: true,
  excludedHostnames: ['\.local'],
  excludedUserAgents: ['Mosaic'],
  disableErrorTracking: false,
  disablePulse: false,
  pulseMaxVirtualPageDuration: 1800000,
  pulseIgnoreUrlCasing: false,
  captureUnhandledRejections: true,
  setCookieAsSecure: false,
  captureMissingRequests: false,
  automaticPerformanceCustomTimings: false
});

RUM API

Tracking Single Page Application (SPA) events

Raygun RUM 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 path set to a string representing the new view or route. RUM 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
  });
});

Angular

export class AppModule implements OnInit {
  constructor(private router: Router) {}
  ngOnInit() {
    this.router.events.subscribe(event => {
      // Track page views when the NavigationEnd event occurs
      if (event instanceof NavigationEnd) {
        rg4js('trackEvent', {
          type: 'pageView',
          path: event.url
        });
      }
    });
  }
}

Tracking custom timings

Custom timings allow you to track custom performance measurements across your website and application. For example, you can track the time it takes for a video to play after the user clicks a button or the time for a component to mount.

  rg4js('trackEvent', {
      type: 'customTiming',
      name: 'firstInput',
      duration: 1200,
  });

You can read more about custom timings on its documentation page here.

Legacy custom timings API

Note: This API has since been deprecated and will be removed in a future version of the provider. We recommend developers upgrade to using the latest version which is both easier to setup and works for single page applications.

rg4js('options', {
  pulseCustomLoadTimeEnabled: true
  // Plus any other configuration options
});

rg4js('trackEvent', {
  type: 'customTimings',
  timings: {
    custom1: 10,
    custom2: 20,
    custom3: 30,
    custom4: 40,
    custom5: 50,
    custom6: 60,
    custom7: 70,
    custom8: 80,
    custom9: 90,
    custom10: 10,
  }
});

These should be called if needed during your page's lifecycle:

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

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

rg4js('disableAutoBreadcrumbsConsole') - Disable just automatic breadcrumb creation from console messages

rg4js('disableAutoBreadcrumbsNavigation') - Disable just automatic breadcrumb creation from navigation events

rg4js('disableAutoBreadcrumbsClicks') - Disable just automatic breadcrumb creation from element clicks

rg4js('disableAutoBreadcrumbsXHR') - Disable just automatic breadcrumb creation XMLHttpRequests

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

rg4js('setAutoBreadcrumbsXHRIgnoredHosts', []) - This can be set to an array of hostnames to not create a breadcrumb for requests/responses to. The values inside the array can either be strings that an indexOf check against the host is made, or regexes which is matched against the host.

rg4js('setBreadcrumbLevel', 'warning') - 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. Valid values are one of ['debug', 'info', 'warning', 'error']. Defaults to info.

rg4js('logContentsOfXhrCalls', true) - 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

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

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

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

You may use the above argument format

Unhandled Promise Rejection

As of 2.10.0 Raygun4JS captures unhandled promise rejections automatically. Browser support for this feature is currently spotty and you can view browser support at MDN.

To disable this functionality by default you can set the captureUnhandledRejections key in the [Initialization Options](Initialization Options).

If you are using a Promise library which contains a global hook for capturing errors you can manually send errors inside of that global hook.

RSVP.js example:

RSVP.on('error', function(reason) {
    rg4js('send', {
      error: reason
    });
});

Promise libraries which report unhandled rejections to a global unhandledrejection DOM event, like Bluebird, are automatically picked up when you have captureUnhandledRejections set.

Dynamic code splitting / loading with Webpack

If you are using Webpack to perform dynamic code splitting / loading and you are loading your bundles off of a separate domain (ie a cdn) you will need to ensure that you have set the output.crossOriginLoading configuration option to anonymous to have Raygun4JS pick up your errors without CORS issues. Without this setting the dynamic script tags will be created without a crossorigin attribute and be treated by the browser as private information in Raygun4JS's execution context.

Example Webpack config

module.exports = {
  // Other webpack config options
  output: {
    // Other output options
    crossOriginLoading: 'anonymous'
  },
};

Payload size conservation

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 when using V2, call this once the page is loaded:

var raygun = rg4js('getRaygunInstance');

You can also provide a callback with 'getRaygunInstance' and it will be called after raygun4js has loaded with the Raygun instance as an argument:

rg4js('getRaygunInstance', raygun => {
});

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 (intact or mutated as per your needs), or 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);

onBeforeSendRUM

rg4js('onBeforeSendRUM', 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 any Real User Monitoring events are 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 (intact or mutated as per your needs), or 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. 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('onBeforeSendRUM', 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 RUM 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.

Note: navigator.sendBeacon is used to send RUM payloads when a page is unloading. In these cases the onBeforeXHR method will not be executed as there is no XHR to reference and no additional headers can be attached.

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

On initialization:

Custom data variables (objects, arrays etc) can be added by calling the withCustomData function on the Raygun object:

rg4js('withCustomData', { foo: 'bar' });

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

Providing custom data with a callback

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

var desiredNum = 1;

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

rg4js('withCustomData', getMyData);

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 initialization:

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

During a send:

Pass tags in using an options object:

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

Customers

By default Raygun4JS assigns a unique anonymous ID for the current user. This is stored in local storage and will default back to using a cookie if local storage is not supported. You can remove the ID from storage by calling:

rg4js('getRaygunInstance').resetAnonymousUser();

Disabling anonymous user tracking

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

Rich user data/user tracking

You can provide additional information 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 of the public function and the options object above is:

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

user|identifier 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 Customers.

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, the Customers feature is disabled. 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.

Ending a session

To end a user's current session:

rg4js('endSession');

This will end the session for a user and start a new one. The new session will remain attached to the current user.

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)

Source maps support

Raygun4JS now 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 Raygun souce maps documentation for more information.

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 change it:

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 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 by settings this:

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.

Angular

You can extend the Angular error handler to send errors directly to Raygun.

// Create a new ErrorHandler and report an issue straight to Raygun
export class RaygunErrorHandler implements ErrorHandler {
  handleError(e: any) {
    rg4js('send', {
      error: e,
    });
  }
}

Vue.js

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

For Vue.js 2.x, this can be done by setting a global error handler on the Vue.config.errorHandler property.

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

For Vue.js 3.x, the .config property is part of the application instance. You will need to create your application instance first before you can assign the errorHandler property.

// Vue 3.x example
const app = Vue.createApp({});

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

app.mount('#app');

Release History

View the changelog here

changelog

Changelog

All notable changes to this project are documented in this file.

[3.1.3]

Changed

  • Updated RUM XHR events to include requestDetails for the onBeforeSendRUM handler. Request details include url (including query parameters), method, body and responseBody. These details are stripped from the payload before it's sent to Raygun's servers.

[3.1.2]

Changed

  • Updated when ping happens so it only happens once, and when successful, it will store in sessionStorage and not ping again. This is to prevent multiple pings from happening on every page load.

[3.1.1]

Fixed

  • Resolved jQuery isFunction deprecation warnings. As of jQuery 3.3, jQuery.isFunction() is deprecated. It is replaced by typeof x === "function" - source.

[3.1.0]

Added

  • Added a ping to tell Raygun that raygun4js has been set up correctly. The ping is enabled by default but can be disabled using the new sendPing option e.g., rg4js('sendPing', false). The ping contains the version of Raygun4js and which products have been enabled (CrashReporting and/or Real User Monitoring). This information will be used to help users when setting up a new application.
  • Moved the typescript types into the main raygun4js repo
  • Added a new option for enabling Real User Monitoring. rg4js('enableRealUserMonitoring', true);

[3.0.1]

Fixed

  • Fixed an typo raised by issue #508 that caused breadcrumb messages to be undefined

[3.0.0]

Added

  • Adds Browserify support to build pipeline
  • Added new browser mocks for unit tests
  • Added new popstate event listener, to trigger
  • unloadHandler replacement: Added popstate event listener network logic to better support mobile devices
  • unloadHandler replacement: Added hidden visibilityState change network logic to better support mobile devices

Changed

  • Changed the way the web-vitals library is imported into the project
  • Moved to using the official web vital callback triggers
  • Updated the sendCoreWebVitalTimings method to fire web vital payloads using beacon if available
  • Upgrade chromedriver dependency to 119.0.1

Removed

  • unloadHandler replacement: Removed the unload event listener network logic in favour of other approaches

[2.28.0]

Changed

  • Adds client provider (version) information
  • Adds defaults for timing information payload information

[2.27.3]

Changed

  • Fixes a rare condition with UMD where we assume rg4js is initialised but it is not, causing an infinite loop.

[2.27.2]

Changed

  • Rolls back the previous change

[2.27.1]

Changed

  • Fixes a rare condition where 'Custom timings' are showing on pages that aren't related

2023-08-28 Update

[2nd phase of deprecations] NPM and nuget packages (2.26.4 and older) were marked deprecated on NPM and Nuget with message:

This package is deprecated. It may not perform completely in browsers newer than Chromium 114

2023-08-21 Update

NPM and nuget packages (2.25.4 and older) were marked deprecated on NPM and Nuget with message:

This package is deprecated. It may not perform completely in browsers newer than Chromium 114

[2.27.0]

Changed

  • Page timings are now gathered by default from PerformanceNavigationTiming instead of PerformanceTiming when available. This was done because the PerformanceTiming API has been deprecated.
  • Now defaults to using the PerformanceObserver object to trigger RUM. This ensures it occurs after the page is fully loaded and all timing objects are populated

Fixed

  • Fixed bug that could stop captureMissingRequests from being set.
  • Fixed potential access to PerformanceTiming API in browsers where it has been deprecated

v2.26.6

Fixed

  • Bug fix for structuredClone causing errors when used, together, with rg4js('withTags', function() {});

v2.26.5

Changed

  • Use api.raygun.io endpoint, if URL is not overridden, to send stored events

v2.26.4

Fixed

  • Reverted the default endpoint url from api.raygun.com back to api.raygun.io (From release v2.26.2 which is causing disruptions for some users)

v2.26.3

Changed

  • The 'OnBeforeSend' and 'OnBeforeSendRUM' callbacks now pass a clone of the payload, to prevent accidental pollution of global objects
  • Updated the Github Action (Pre commit unit tests) Node to version 20

v2.26.2

Fixed

  • Replaced old company name in metadata
  • Documentation points to 'new' .com url

Changed

  • Updated the Raygun url to send events to preferred ingestion endpoint

v2.26.1

Fixed

  • Fixed timing bug, where some xhr requests may rarely be mis-attributed to a different page from which they were started on.

Changed

  • Updated unit test libraries and re-enabled running on PR creation

v2.26.0

v2.25.8

  • Improve README documentation to be more clear on the protocol relative URL and how to use the CDN implementation without running a server .

v2.25.7

  • Improve README documentation to be more clear on our highly recommended installation steps.
  • Minor grammar changes within README
  • Add a note about rich user data within README
  • Update the Github Workflow to use a support chrome-version for the chromedriver

v2.25.6

  • Improved support for including High Entropy user agent data

v2.25.5

  • Adds support for including High Entropy user agent data

v2.25.4

  • Adds support for the Ionic Capacitor cross-platform app runtime

v2.25.3

  • Allows passing a callback with 'getRaygunInstance' to allow for easier access to checking if a raygun instance exists when raygun4js may not have finished loading

v2.25.2

  • Fixes an issue where the rg4js proxy in the umd loader was throwing away the return value of the executor, preventing the use of commands like 'getRaygunInstance'

v2.25.1

  • Fixes an issue where errors on promises, which have been caught, were still being reported to raygun. Thanks @codex- for identifying and fixing the problem.

v2.25.0

  • Attach a parent resource to non-page load events to assist with resource parenting.

v2.24.0

  • Send the browser's viewport width and height with each RUM session payload.

v2.23.0

  • If ignore3rdPartyErrors option is true, discard errors that match the pattern of errors from browser extensions, bots and crawlers.

v2.22.5

  • Fixes an issue with Core Web Vital tracking not being able to be disabled.
  • Fixes an issue where navigator.sendBeacon errors were not being handled gracefully.

v2.22.4

  • Upgrade the web-vitals vendor library to v2.1.0.
  • Fixes an issue where Core Web Vital timings were being queued behind virtual page timings.

v2.22.3

  • Fixes an issue where the heartbeat was not clearing the xhrStatusMap array due to this referring to the window object

v2.22.2

  • Fixes an issue where raygun4js attempts to access the document on non-browser environments. Also ensures that the Core Web Vitals scripts are not initialized for these environments.

v2.22.1

  • Fixes a compatibility issue with the web-vitals vendor script and RequireJS.

v2.22.0

  • Adds the ability to track Core Web Vitals when the trackCoreWebVitals option is enabled. The option is enabled by default.

v2.21.1

  • Fixes an issue where errors generated on Cordova iOS 6.0+ applications would not contain a stack trace due to the scheme changing from file and to app

v2.21.0

  • Fixes a memory leak issue by clearing the xhrStatusMap array on every heart beat
  • Replace the "Script error" message on an unhandled rejection to be "Unhandled promise rejection" to better distinguish between the two

v2.20.3

  • Adds a fallback for calculating the duration for timing entries which have a .duration value of zero. This fixes a issue where Safari reports fetch calls as having a duration of zero.

v2.20.2

  • Fixes an issue with ionic-cordova errors not reporting due to the stack-trace being null. Thanks @nirajrajbhandari for identifying and fixing the problem

v2.20.1

  • Fixes an issue where some browsers (most notably Mobile Safari) won't send data when the page is being transitioned away from

v2.20.0

  • Adds new custom timings support which enables Custom Timings to work with SPA's and regardless of page loads
  • Adds an option automaticPerformanceCustomTimings for tracking performance.measure calls as custom timings

v2.19.1

  • Fix accidental removal of node.value

v2.19.0

  • Add manual end session functionality to public API

v2.18.4

  • Fixes an issue where we record the "navigation" entryTypes as cached child assets
  • Fixes an issue with setAutoBreadcrumbsXHRIgnoredHosts not being applied when requests are opened

v2.18.3

  • Use navigator.sendBeacon when available to send the last request as XHR requests can be cancelled

v2.18.2

  • Fixes an issue with first-paint being calculated incorrectly for Edge/IE browsers

v2.18.1

  • Fixes an issue with how the network tracking util integrates with the fetch snippet

v2.18.0

  • Missing XHR timings are no longer tracked by default. Instead a configuration option exists to enable these via 'captureMissingRequests'
  • Set the maximum duration of missing XHR calls to 5 minutes
  • Add offset timings to missing XHR calls
  • Support for tracking fetch methods which might be referenced locally

v2.17.2

  • Fixes an issue where the XHR data type was not attached to statusCode calls

v2.17.1

  • Fix regression and use localStorage to persist RUM sessions instead of sessionStorage

v2.17.0

  • Add initial support for users to set the client IP address

v2.16.1

  • Fix promise rejection errors when trying to retrieve fetch response text in network-tracking module

v2.16.0

  • Add paint timings to RUM page load metrics using the performance api & msFirstPaint
  • Wrap response code get 'text' in a try catch

v2.15.3

  • Change the key for the status code which gets sent to RUM to statusCode to match the API
  • Prepend the protocol to the URL in the resolveFullUrl function to accommodate URLs without protocols

v2.15.2

  • Include all dist files in npm package instead of just main file
  • Don't run RUM in React Native to prevent a crash, RUM does not support React Native

v2.15.1

  • Fix error in Raygun4JS UMD build with raygunNetworkTrackingFactory being undefined

v2.15.0

  • Use localStorage to persist user id for Crash Reporting instead of a cookie
  • Use sessionStorage to persist session id for RUM instead of a cookie
  • Start tracking XHR status codes with performance information

v2.14.1

  • Improve support for EmberJS

v2.14.0

  • Add fetch support to automatic XHR breadcrumbs

v2.13.4

  • Fix offline errors not being sent with new API key format

v2.13.3

  • Guard call to XMLHttpRequest.setRequestHeader as it is not present on IE8,9,10,11

v2.13.2

  • Typescript definitions removed, they are now maintained in @types/raygun4js

v2.13.1

  • Set content-type header on XHR calls
  • Fix issue #302 with the promiseRejectionHandler throwing rejection errors

v2.13.0

  • Unhandled promise exceptions will now use the look for a reason.error error instance if event.reason isn't already an Error instance.

v2.12.1

  • Bug where stacktraces/messages in older browsers wouldn't be calculated

v2.12.0

  • Add UnhandledPromiseRejection tag to errors caught by the unhandled promise callback
  • Fixes a bug where the UnhandledException tag would be added unnecessarily to subsequent errors
  • Manually sending a error which is a string and not a Error object no longer results in a Script error being sent. Instead it uses the string as the error message

v2.11.1

  • Fixes bug with ignore3rdPartyErrors that could result in first party errors being ignored
  • Fixes Typescript definitions for V2 API

v2.11.0

  • Adds 'setCookieAsSecure' option which will set the '; secure' flag on cookies. Off by default

v2.10.1

  • Fetch calls are now tracked like XHR calls for RUM

v2.10.0

  • Add support for unhandled promise exceptions

v2.9.4

  • Fix crash with stack traces containing undefined urls

v2.9.2

  • Fix potential error attaching breadcrumbs to error payload

v2.9.1

  • Fixes crash in third party error detection code when stacktraces have undefined urls

v2.9.0

  • If logging of XHR contents in Breadcrumbs is enabled requests/responses before the onload event will now be recorded
  • Errors that happen before onload event when using Raygun4JS via the NPM module will now be captured

v2.8.6

  • Add a request ID for each page and virtual page to associate it with its child assets
  • Add failed posted payload event items to a queue, attempt to send queued items on heartbeat

v2.8.5

  • Navigating to virtual pages before sending custom timings will no longer prevent the page load timings from being sent
  • Stop multiple heartbeat timers from being created
  • Prevent 'page' and 'virtual page' timings from being included in the same event data item, fixing 'virtual pages' being counted as 'page views'
  • Fix child assets being associated with incorrect views
  • Fix virtual page duration timings

v2.8.4

  • Correct error in Typescript definition requiring isAnonymous to be a string when setting user information

v2.8.3

  • Fix crash on unhandled exceptions when withTags option is set to a string instead of an array or function returning an array

v2.8.2

  • Fix JSON parsing issue when attempting to use RUM custom timings

v2.8.1

  • Strip query string out of RUM virtual page urls

v2.8.0

  • New onBeforeSendRUM callback to modify and cancel sending of RUM payloads

v2.7.2

  • Disabling automatic breadcrumb functionality will correctly un-enhance the enhanced objects

v2.7.1

  • Don't read response text in breadcrumb XHR logging if logXhrContents is false
  • Improve breadcrumb disabling to handle network calls that match xhrIgnoredHosts but were triggered before the xhrIgnoredHosts configuration option was set
  • Update TraceKit regexes to handle stacktraces in RN android release builds

v2.6.7

  • Fix a rare initialization issue with RUM and recording events before the provider has finished loading
  • Small bugfixes to some of the Breadcrumbs operations

v2.6.6

  • Fixes a runtime bug on init when using the UMD module (installed via NPM) introduced in 2.6.2

v2.6.5

  • React Native: bugfix for 'window is not defined' error upon import

v2.6.4

  • Fix a bug in vanilla and UMD builds introduced when using breadcrumbs

v2.6.3

  • Adds support for tracking custom timings in Real User Monitoring

v2.6.2

  • Fixes corner case bugs with XHRs as recorded by breadcrumbs

v2.6.1

  • Adds breadcrumbs feature

v2.6.0

  • Initial beta support for React Native in Release (production) mode
  • Fixed indexOf bug for IE8 compatibility

v2.5.3

  • Fixed offline errors failing to send to Raygun when back online.

v2.5.2

  • Fix for duplicate UnhandledException tags as added in v2.5.0

v2.5.1

  • Loader option setters and errors/trackEvent calls are now executed once onLoad, fixing edge cases and race conditions with rg4js calls during various stages of the page lifecycle

v2.5.0

  • Unhandled errors now have a tag added, UnhandledException, for filtering by handled error vs. crash in the Raygun web app
  • Update regexes to support stacktraces from Electron, Chrome with Webpack, and many other scenarios/edge cases
  • Locally cached errors for offline saving are now keyed off the API key, allowing apps running on different subdomains to use offline caching
  • Adds UMD module support for React Native and other non-web bundled app scenarios

v2.4.3

  • Max length of RUM URLs is clamped to 800 chars (aligned with existing backend behavior)
  • Guard against an undefined options object causing undefined messages for thrown non-Error objects (strings)

v2.4.2

  • Fix synchronous XHR warnings in Chrome

v2.4.1

  • Fix a bug in v2.4.0 when the library loads first and consumer code sets rg4js options which then aren't picked up and used

v2.4.0

  • Allow send/trackEvent calls to be proxied through rg4js() to avoid async loading race condition when global Raygun object not available before static load is finished
  • Add onAfterSend callback function
  • Fix non-RG onerror handlers from being removed if Crash Reporting not enabled

v2.3.4

  • The most recent pending virtual page is now sent when the tab/window is closed from unload (where available)

v2.3.3

  • RUM URLs lowercase by default

v2.3.2

  • Add ability to ignore RUM URL casing

v2.3.1

  • Guard against undefined fetchStart bug in Mobile Safari 8.0 which passed the existing Browser Timing checks

v2.3.0

  • Add new onBeforeXHR function for mutating the XHR object immediately before an error payload is sent to the API
  • If invalid non-function handler passed in to jQuery Ajax add function, call the old event handler & return early
  • CustomData keys with a value of null are now included and not filtered out automatically when filtering is enabled
  • Guard against non-string type in message being sub-stringed
  • Fix bug when passing callback to withTags() and subsequently calling Raygun.send() with tags parameter also
  • ignoreAjaxAbort now checks for statusCode of 0 in addition to checking if the response headers are null when deciding to ignore a potential aborted Ajax request

v2.2.3

  • Further guards for unsupported now() in Safari 7/8

v2.2.2

  • Hotfix for unsupported calls in IE8

v2.2.1

  • Release version of v2.2.0-beta with bug fixes and improvements; trackEvent officially added to API

v2.2.0-beta

  • Adds experimental support for SPA sites to RUM
  • noConflict mode improved for V2
  • Fixed a bug when attaching onBeforeUnload handler when RUM enabled

  • v2.1.1

    • Fix issue where when filterScope set to 'all' resulted in payload 400 errors
    • Guard against null message substring error

v2.1.0

  • Add custom grouping key function
  • Add ability to ignore host-names and user agents for RUM
  • Calls to rg4js() for config setters made after the script has been downloaded by the snippet are now proxied through to the Raygun object, making the V2 API experience like V1
  • Guard against data set with V2 API being null for certain out-of-order declaration scenarios
  • Fix API rejection issue for large heartbeat payloads
  • Fix a bug where the session cookie was not present or invalid

v2.0.3

  • Fixes a snippet loader race condition

  • v2.0.2

    • Fixes an issue with isAnonymous from setUser
  • v2.0.1

    • Guard against NaNs in RUM timing data

v2.0.0

  • Adds support for Real User Monitoring

v1.18.7

  • Create copy of customData object when filtering

v1.18.6

  • Slice function check for older browsers

v1.18.5

  • Limit active data on JQuery AJAX errors

v1.18.4

  • Error payloads are no longer persisted in localStorage if sending failed due to RG plan hitting its monthly cap
  • Guard against invalid JSON being persisted in localStorage on send failure
  • Guard against incorrect (non-function) types being passed in as callback handler to wrapped $.event
  • Guard against null stacktraces in JS Windows Store apps

v1.18.3

  • Published to npm
  • Ajax errors: custom data now includes the markup of the tag which caused the error
  • Various improvements to the internal Tracekit fork for Firefox and Chrome
  • Added generation of source maps

v1.18.2

  • Safer implementations of excludedHostnames and excludedUserAgents when there are prototype functions on the arrays passed to these keys

v1.18.1

  • filterSensitiveData now also accepts RegExp objects in its param array

v1.18.0

  • Add new setFilterScope() function for supporting applying the filterSensitiveData keys across the entire payload (supported scopes are 'all' and 'customData')

v1.17.0

  • Add location.hash to Request.Url before payload is sent

v1.16.2

  • setUser now accepts empty strings/falsey values for logout scenarios
  • Max message size of 512 in payload

v1.16.1

  • Guard against a runtime error when no options are specified

v1.16.0

  • Add new ignoreAjaxError option to stop auto sending of Ajax 400/500 errors when attached
  • excludedHostnames now takes regexes for partial matching
  • Add new excludedUserAgents to prevent sends from certain clients (supports regexes as above)

v1.15.0

  • Support multiple Raygun objects on one page
  • jQuery Ajax errors now have better method names (the function signature) for anonymous functions
  • Added init option to exclude host-names to prevent sending from certain environments
  • wrapAsynchronousCallbacks now defaults to false
  • Split the changelog out into this file

v1.14.0

  • Add wrapAsynchronousCallbacks option for disabling wrapping of setTimeout/setInterval callbacks
  • Provide query-strings from AngularJS too (hash in URL broke previous logic)
  • Fix stacktrace bug from Firefox that caused source maps to not be processed correctly

v1.13.0

  • Added anonymous user tracking, enabled by default
  • Errors in third-party scripts (not hosted on origin domain) are now stopped from being sent correctly (flag still must be set true)

v1.12.0

  • Added new onBeforeSend() callback function
  • withTags() can now take a callback function
  • Custom data is now filtered by filterSensitiveData (recursively) too
  • Guard against 'settings' in ajax errors being undefined, leading to failed sends
  • Add support for unique stack trace format in iOS 7 UIWebView for anonymous functions

v1.11.2

  • Guard against another possible undefined string in Tracekit causing an 'indexOf' error

v1.11.1

  • Ajax errors now transmit response text
  • Filtered keys are now transmitted with the value sanitized instead of having the whole object removed

v1.11.0

  • Add ignoring 3rd party scripts
  • Fix bug with filtering keys on some browsers
  • Support chrome extension stack parsing

v1.10.0

  • Added enhanced affected user data to setUser
  • Ported latest Tracekit improvements

v1.9.2

  • Fix bug in filter query

v1.9.1

  • Added function to filter sensitive query string

v1.9.0

  • Add ignoreAjaxAbort option
  • Provide vanilla build without jQuery hooks

v1.8.4

  • Guard against circular reference in custom data

v1.8.3

  • Allow withCustomData to accept a function to provide a customdata object
  • Fix undefined URL issue from Ajax
  • Rm duplicated Tracekit ajax hook

v1.8.2

  • Fixed bug in Tracekit which caused 'Cannot call method indexOf' of undefined error

v1.8.1

  • Added meaningful message for Ajax errors
  • Fixed debugmode logging bug

v1.8.0

  • Add Offline Saving feature; add support for WinJS

v1.7.2

  • Fixed tags not being included when error caught from global window.onerror handler

v1.7.1

  • Fixed broken withTags when no other custom data provided on Send

v1.7.0

  • Added source maps support by transmitting column numbers (from supported browsers)

v1.6.1

  • Fixed an issue with not supplying options to processUnhandledException

v1.6.0

  • Added support for attaching Tags
  • Added NuGet package

v1.5.2

  • Added Bower package; minor bugfix for Ajax functionality

v1.5.1

  • Capture data submitted by jQuery AJAX calls

v1.5.0

  • Allow IE8 to submit errors over HTTP
  • Updated TraceKit to the latest revision

v1.4.1

  • Fix bug with using jQuery AJAX calls with >= v1.5 of jQuery

v1.4.0

  • AJAX errors will display status code instead of script error

v1.3.3

  • Fixed regression where send() would no longer attach a custom data object parameter

v1.3.2

  • Fixed the need to call attach() (if only using manual sending)

v1.3.1

  • Added user tracking/Customers and version tracking functionality

v1.3.0

  • Updated to latest TraceKit
  • Included removed jQuery support from TraceKit

v1.2.1

  • Added jQuery AJAX error support

v1.2.0

  • Changed from QueryString approach to sending data to using an ajax post with CORS

v1.0.1

  • Initial Release