latest PDF - Read the Docs

raven-js Documentation
Release 1.1.16
Matt Robenolt
January 28, 2015
Contents
1
Getting Started
1.1 Installation .
1.2 Plugins . . .
1.3 Configuration
1.4 Usage . . . .
1.5 Pro Tips™ .
.
.
.
.
.
3
3
4
4
7
10
2
Developers
2.1 Contributing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
13
13
3
What’s New?
3.1 Changelog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
15
15
4
Resources
19
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
i
ii
raven-js Documentation, Release 1.1.16
Raven.js is a tiny standalone JavaScript client for Sentry.
This version of Raven.js requires Sentry 6.0 or newer.
Contents
1
raven-js Documentation, Release 1.1.16
2
Contents
CHAPTER 1
Getting Started
1.1 Installation
Raven is distributed in a few different methods, and should get included after any other libraries are included, but
before your own scripts.
So for example:
<script src=’’jquery.js’’></script>
<script src=’’//cdn.ravenjs.com/1.1.16/jquery,native/raven.min.js’’></script>
<script>Raven.config(‘...’).install();</script>
<script src=’’app.js’’></script>
This allows the ability for Raven’s plugins to instrument themselves. If included before something like jQuery, it’d be
impossible to use for example, the jquery plugin.
1.1.1 Using our CDN
We serve our own builds off of Fastly. They are accessible over both http and https, so we recommend leaving the
protocol off.
Our CDN distributes builds with and without plugins.
<script src=’’//cdn.ravenjs.com/1.1.16/raven.min.js’’></script>
We highly recommend trying out a plugin or two since it’ll greatly improve the chances that we can collect good
information.
This version does not include any plugins. See ravenjs.com for more information about plugins and getting other
builds.
1.1.2 Bower
We also provide a way to deploy Raven via bower. Useful if you want serve your own scripts instead of depending
on our CDN and mantain a bower.json with a list of dependencies and versions (adding the --save flag would
automatically add it to bower.json).
$ bower install raven-js --save
<script src="/bower_components/raven-js/dist/raven.js"></script>
Also note that the file is uncompresed but is ready to pass to any decent JavaScript compressor like uglify.
3
raven-js Documentation, Release 1.1.16
1.1.3 Requirements
Raven expects the browser to provide window.JSON and window.JSON.stringify. In Internet Explorer 8+ these are
available in standards mode. You can also use json2.js to provide the JSON implementation in browsers/modes which
doesn’t support native JSON
1.2 Plugins
1.2.1 What are plugins?
In Raven.js, plugins are little snippets of code to augment functionality for a specific application/framework. It is
highly recommended to checkout the list of plugins and use what apply to your project.
In order to keep the core small, we have opted to only include the most basic functionality by default, and you can
pick and choose which plugins are applicable for you.
1.2.2 Why are plugins needed at all?
JavaScript is pretty restrictive when it comes to exception handling, and there are a lot of things that make it difficult
to get relevent information, so it’s important that we inject code and wrap things magically so we can extract what we
need. See Usage for tips regarding that.
1.2.3 All Plugins
• https://github.com/getsentry/raven-js/tree/master/plugins
• Download
1.3 Configuration
We must first configure Sentry to allow certain hosts to report errors. This prevents abuse so somebody else couldn’t
start sending errors to your account from their site.
Note: Without setting this, all messages will be rejected!
This can be found under the Project Details page in Sentry.
Now need to set up Raven.js to use your Sentry DSN.
Raven.config(’https://[email protected]/1’).install()
At this point, Raven is ready to capture any uncaught exception.
Although, this technically works, this is not going to yield the greatest results. It’s highly recommended to next check
out Usage.
1.3.1 Optional settings
Raven.config() can be passed an optional object for extra configuration.
4
Chapter 1. Getting Started
raven-js Documentation, Release 1.1.16
logger
The name of the logger used by Sentry. Default: javascript
{
logger: ’javascript’
}
tags
Additional tags to assign to each event.
{
tags: {git_commit: ’c0deb10c4’}
}
whitelistUrls
The inverse of ignoreUrls. Only report errors from whole urls matching a regex pattern or an exact string.
whitelistUrls should match the url of your actual JavaScript files. It should match the url of your site if and
only if you are inlining code inside <script> tags.
Does not affect captureMessage or when non-error object is passed in as argument to captureException.
{
whitelistUrls: [/getsentry\.com/, /cdn\.getsentry\.com/]
}
ignoreErrors
Very often, you will come across specific errors that are a result of something other than your application, or errors
that you’re completely not interested in. ignoreErrors is a list of these messages to be filtered out before being sent to
Sentry as either regular expressions or strings.
Does not affect captureMessage or when non-error object is passed in as argument to captureException.
{
ignoreErrors: [’fb_xd_fragment’]
}
ignoreUrls
The inverse of whitelistUrls and similar to ignoreErrors, but will ignore errors from whole urls matching
a regex pattern or an exact string.
{
ignoreUrls: [/graph\.facebook\.com/, ’http://example.com/script2.js’]
}
Does not affect captureMessage or when non-error object is passed in as argument to captureException.
1.3. Configuration
5
raven-js Documentation, Release 1.1.16
includePaths
An array of regex patterns to indicate which urls are a part of your app in the stack trace. All other frames will appear
collapsed inside Sentry to make it easier to discern between frames that happened in your code vs other code. It’d be
suggested to add the current page url, and the host for your CDN.
{
includePaths: [/https?:\/\/getsentry\.com/, /https?:\/\/cdn\.getsentry\.com/]
}
dataCallback
A function that allows mutation of the data payload right before being sent to Sentry.
{
dataCallback: function(data) {
// do something to data
return data;
}
}
shouldSendCallback
A callback function that allows you to apply your own filters to determine if the message should be sent to Sentry.
{
shouldSendCallback: function(data) {
return false;
}
}
maxMessageLength
By default, raven truncates messages to a max length of 100 characters. You can customize the max length with this
parameter.
1.3.2 Putting it all together
<!DOCTYPE html>
<html>
<head>
<title>Awesome stuff happening here</title>
</head>
<body>
...
<script src=’’jquery.min.js’’></script>
<script src=’’//cdn.ravenjs.com/1.1.16/jquery,native/raven.min.js’’></script>
<script>
var options = {
logger: ‘my-logger’,
whitelistUrls: [
/disqus\.com/, /getsentry\.com/
6
Chapter 1. Getting Started
raven-js Documentation, Release 1.1.16
],
ignoreErrors: [
‘fb_xd_fragment’, /ReferenceError:.*/
],
includePaths: [
/https?:\/\/(www\.)?getsentry\.com/
]
};
Raven.config(‘https://[email protected]/1’, options).install();
</script>
<script src=’’myapp.js’’></script>
</body>
</html>
1.3.3 TraceKit specific optional settings
Usually there is no need to touch these settings, but they exist in case you need to tweak something.
fetchContext
Enable TraceKit to attempt to fetch source files to look up anonymous function names, this can be useful to enable if
you don’t get the context for some entries in the stack trace. Default value is false.
{
fetchContext: true
}
linesOfContext
The count of lines surrounding the error line that should be used as context in the stack trace, default value is 11. Only
applicable when ‘‘fetchContext‘ is enabled.
{
linesOfContext: 11
}
collectWindowErrors
Enable or disable the TraceKit window.onerror handler, default value is true.
{
collectWindowErrors: true
}
1.4 Usage
By default, Raven makes a few efforts to try its best to capture meaningful stack traces, but browsers make it pretty
difficult.
The easiest solution is to prevent an error from bubbling all of the way up the stack to window.
1.4. Usage
7
raven-js Documentation, Release 1.1.16
1.4.1 How to actually capture an error correctly
try...catch
The simplest way, is to try and explicitly capture and report potentially problematic code with a try...catch block
and Raven.captureException.
try {
doSomething(a[0])
} catch(e) {
Raven.captureException(e)
}
Do not throw strings! Always throw an actual Error object. For example:
throw new Error(’broken’)
throw ’broken’ // bad
// good
It’s impossible to retrieve a stack trace from a string. If this happens, Raven transmits the error as a plain message.
context/wrap
Raven.context allows you to wrap any function to be immediately executed. Behind the scenes, Raven is just
wrapping your code in a try...catch block to record the exception before re-throwing it.
Raven.context(function() {
doSomething(a[0])
})
Raven.wrap wraps a function in a similar way to Raven.context, but instead of executing the function, it returns
another function. This is totally awesome for use when passing around a callback.
var doIt = function() {
// doing cool stuff
}
setTimeout(Raven.wrap(doIt), 1000)
1.4.2 Tracking authenticated users
While a user is logged in, you can tell Sentry to associate errors with user data.
Raven.setUserContext({
email: ’[email protected]’,
id: ’123’
})
If at any point, the user becomes unauthenticated, you can call Raven.setUserContext() with no arguments
to remove their data. This would only really be useful in a large web app where the user logs in/out without a page
reload.
1.4.3 Capturing a specific message
Raven.captureMessage(’Broken!’)
8
Chapter 1. Getting Started
raven-js Documentation, Release 1.1.16
1.4.4 Passing additional data
captureException, context, wrap, and captureMessage functions all allow passing additional data to be
tagged onto the error, such as tags or extra for additional context.
Raven.captureException(e, {tags: { key: "value" }})
Raven.captureMessage(’Broken!’, {tags: { key: "value" }})
Raven.context({tags: { key: "value" }}, function(){ ... })
Raven.wrap({logger: "my.module"}, function(){ ... })
Raven.captureException(e, {extra: { foo: "bar" }})
You can also set context variables globally to be merged in with future exceptions with setExtraContext and
setTagsContext.
Raven.setExtraContext({ foo: "bar" })
Raven.setTagsContext({ key: "value" })
1.4.5 Getting back an event id
An event id is a globally unique id for the event that was just sent. This event id can be used to find the exact event
from within Sentry.
This is often used to display for the user and report an error to customer service.
Raven.lastEventId()
Raven.lastEventId() will be undefined until an event is sent. After an event is sent, it will contain the string id.
Raven.captureMessage(’Broken!’)
alert(Raven.lastEventId())
1.4.6 Check if Raven is setup and ready to go
Raven.isSetup()
1.4.7 Dealing with minified source code
Raven and Sentry now support Source Maps.
We have provided some instructions to creating Source Maps over at https://www.getsentry.com/docs/sourcemaps/.
Also, checkout our Gruntfile for a good example of what we’re doing.
You can use Source Map Validator to help verify that things are correct.
1.4.8 CORS
If you’re hosting your scripts on another domain and things don’t get caught by Raven, it’s likely that the error will
bubble up to window.onerror. If this happens, the error will report some ugly Script error and Raven will
drop it on the floor since this is a useless error for everybody.
1.4. Usage
9
raven-js Documentation, Release 1.1.16
To help mitigate this, we can tell the browser that these scripts are safe and we’re allowing them to expose their errors
to us.
In your <script> tag, specify the crossorigin attribute:
<script src="//cdn.example.com/script.js" crossorigin="anonymous"></script>
And set an Access-Control-Allow-Origin HTTP header on that file.
Access-Control-Allow-Origin: *
Note: both of these steps need to be done or your scripts might not even get executed
1.5 Pro Tips™
1.5.1 Decluttering Sentry
The first thing to do is to consider constructing a whitelist of domains in which might raise acceptable exceptions.
If your scripts are loaded from cdn.example.com and your site is example.com it’d be reasonable to set
whitelistUrls to:
whitelistUrls: [
/https?:\/\/((cdn|www)\.)?example\.com/
]
Since this accepts a regular expression, that would catch anything *.example.com or example.com exactly. See also:
Config: whitelistUrls.
Next, checkout the list of plugins we provide and see which are applicable to you.
The community has compiled a list of common ignore rules for common things, like Facebook, Chrome extensions,
etc. So it’s recommended to at least check these out and see if they apply to you. Check out the original gist.
var ravenOptions = {
ignoreErrors: [
// Random plugins/extensions
’top.GLOBALS’,
// See: http://blog.errorception.com/2012/03/tale-of-unfindable-js-error. html
’originalCreateNotification’,
’canvas.contentDocument’,
’MyApp_RemoveAllHighlights’,
’http://tt.epicplay.com’,
’Can\’t find variable: ZiteReader’,
’jigsaw is not defined’,
’ComboSearch is not defined’,
’http://loading.retry.widdit.com/’,
’atomicFindClose’,
// Facebook borked
’fb_xd_fragment’,
// ISP "optimizing" proxy - ‘Cache-Control: no-transform‘ seems to reduce this. (thanks @acdha)
// See http://stackoverflow.com/questions/4113268/how-to-stop-javascript-injection-from-vodafon
’bmi_SafeAddOnload’,
’EBCallBackMessageReceived’,
// See http://toolbar.conduit.com/Developer/HtmlAndGadget/Methods/JSInjection.aspx
’conduitPage’
],
ignoreUrls: [
10
Chapter 1. Getting Started
raven-js Documentation, Release 1.1.16
// Facebook flakiness
/graph\.facebook\.com/i,
// Facebook blocked
/connect\.facebook\.net\/en_US\/all\.js/i,
// Woopra flakiness
/eatdifferent\.com\.woopra-ns\.com/i,
/static\.woopra\.com\/js\/woopra\.js/i,
// Chrome extensions
/extensions\//i,
/^chrome:\/\//i,
// Other plugins
/127\.0\.0\.1:4001\/isrunning/i, // Cacaoweb
/webappstoolbarba\.texthelp\.com\//i,
/metrics\.itunes\.apple\.com\.edgesuite\.net\//i
]
};
1.5.2 Sampling Data
It happens frequently that errors sent from your frontend can be overwhelming. One solution here is to only send a
sample of the events that happen. You can do this via the shouldSendCallback setting:
shouldSendCallback: function(data) {
// only send 10% of errors
var sampleRate = 10;
return (Math.random() * 100 <= sampleRate);
}
1.5. Pro Tips™
11
raven-js Documentation, Release 1.1.16
12
Chapter 1. Getting Started
CHAPTER 2
Developers
2.1 Contributing
2.1.1 Setting up an Environment
To run the test suite and run our code linter, node.js and npm are required. If you don’t have node installed, get it here
first.
Installing all other dependencies is as simple as:
$ npm install
And if you don’t have Grunt already, feel free to install that globally:
$ npm install -g grunt-cli
2.1.2 Running the Test Suite
The test suite is powered by Mocha and can both run from the command line, or in the browser.
From the command line:
$ grunt test
From your browser:
$ grunt run:test
Then visit: http://localhost:8000/test/
2.1.3 Compiling Raven.js
The simplest way to compile your own version of Raven.js is with the supplied grunt command:
$ grunt build
By default, this will compile raven.js and all of the included plugins.
If you only want to compile the core raven.js:
13
raven-js Documentation, Release 1.1.16
$ grunt build.core
Files are compiled into build/.
2.1.4 Contributing Back Code
Please, send over suggestions and bug fixes in the form of pull requests on GitHub. Any nontrivial fixes/features
should include tests. Do not include any changes to the dist/ folder or bump version numbers yourself.
Documentation
The documentation is written using reStructuredText, and compiled using Sphinx. If you don’t have Sphinx installed,
you can do it using following command (assuming you have Python already installed in your system):
$ pip install sphinx
Documentation can be then compiled by running:
$ make docs
Afterwards you can view it in your browser by running following command and than pointing your browser to
http://127.0.0.1:8000/:
$ grunt run:docs
2.1.5 Releasing New Version
• Bump version numbers in both package.json and bower.json.
• $ grunt dist This will compile a new version and update it in the dist/ folder.
• Confirm that build was fine, etc.
• Commit new version, create a tag. Push to GitHub.
• $ grunt publish to recompile all plugins and all permutations and upload to S3.
• Confirm that the new version exists behind cdn.ravenjs.com
• Update version in the gh-pages branch specifically for http://ravenjs.com/.
• glhf
14
Chapter 2. Developers
CHAPTER 3
What’s New?
3.1 Changelog
3.1.1 1.1.16
• Fixed a bug that was preventing stack frames from raven.js from being hidden correctly.
https://github.com/getsentry/raven-js/pull/216
See:
• Fixed an IE bug with the console plugin. See: https://github.com/getsentry/raven-js/issues/217
• Added support for chrome-extension:// protocol in Chrome in stack traces.
• Added setExtraContext and setTagsContext. See: https://github.com/getsentry/raven-js/pull/219
• Renamed setUser to setUserContext to match. setUser still exists, but will be deprecated in a future
release.
• New backbone.js plugin. See: https://github.com/getsentry/raven-js/pull/220
• Added support for chrome:// protocol in Firefox in stack traces. See: https://github.com/getsentry/ravenjs/pull/225
• Ignore more garbage from IE cross origin errors. See: https://github.com/getsentry/raven-js/pull/224
• Added Raven.debug to prevent logging to console when false. Defaults to true for backwards compatability. See: https://github.com/getsentry/raven-js/pull/229
• Prevent calling Raven.config() or Raven.install() twice. See: https://github.com/getsentry/ravenjs/pull/233
3.1.2 1.1.15
• Fix issues if a non-string were passed to Raven.captureMessage and non-Error objects were passed to
Raven.captureException.
3.1.3 1.1.14
• Only filter normal Error objects without a message, not all of them. Turns out, people throw errors like this.
Ahem, Underscore.js. See: https://github.com/jashkenas/underscore/pull/1589/files
15
raven-js Documentation, Release 1.1.16
3.1.4 1.1.13
• Fixed a unicode issue in the previous release.
3.1.5 1.1.12
• Fix a bug using the console plugin with older IE. See: https://github.com/getsentry/raven-js/pull/192
• Added initial ember.js plugin for early testing and feedback.
• Added initial angular.js plugin for early testing and feedback.
• Fixed an issue with the require.js plugin basically not working at
https://github.com/getsentry/raven-js/commit/c2a2e2672a2a61a5a07e88f24a9c885f6dba57ae
all.
See:
• Got rid of Raven.afterLoad and made it internal only.
• Raven.TraceKit is now internal only.
• Truncate message length to a max of 100 characters becasue angular.js sucks and generates stupidly large error
messages.
3.1.6 1.1.11
• Capture column number from FireFox
• Fix propagation of extra options through captureException, see: https://github.com/getsentry/ravenjs/pull/189
• Fix a minor bug that causes TraceKit to blow up of someone passes something dumb through
window.onerror
3.1.7 1.1.10
• A falsey DSN value disables Raven without yelling about an invalid DSN.
3.1.8 1.1.9
• Added Raven.lastEventId() to get back the Sentry event
js.readthedocs.org/en/latest/usage/index.html#getting-back-an-event-id
id.
See:
http://raven-
• Fixed a bug in the console plugin. See: https://github.com/getsentry/raven-js/pull/181
• Provide a way out of deep wrapping arguments. See: https://github.com/getsentry/raven-js/pull/182
• Raven.uninstall() actually removes the patched window.onerror.
• No more globally exposed TraceKit!
3.1.9 1.1.8
• Fixed a bug in IE8. See: https://github.com/getsentry/raven-js/pull/179
16
Chapter 3. What’s New?
raven-js Documentation, Release 1.1.16
3.1.10 1.1.4-1.1.7
These were a bunch of super small incremental updates trying to get better integration and better support inside Sentry
itself.
• Culprit determined from the src url of the offending script, not the url of the page.
• Send Sentry the frames in the right order. They were being sent in reverse. Somehow nobody noticed this.
• Support for Chrome’s new window.onerror api. See: https://github.com/getsentry/raven-js/issues/172
3.1.11 1.1.3
• When loading with an AMD loader present, do not automatically call Raven.noConflict(). This was
causing issues with using plugins. See: https://github.com/getsentry/raven-js/pull/165
• https://github.com/getsentry/raven-js/pull/168
3.1.12 1.1.2
• An invalid DSN will now raise a RavenConfigError instead of some cryptic error
• Will raise a RavenConfigError when supplying the private key part of the DSN since this isn’t applicable for
raven.js and is harmful to include
• https://github.com/getsentry/raven-js/issues/128
3.1.13 1.1.1
• Fixed a bug in parsing some DSNs. See: https://github.com/getsentry/raven-js/issues/160
3.1.14 1.1.0
Plugins
If you’re upgrading from 1.0.x, 2 “plugins” were included with the package. These 2 plugins are now stripped out
of core and included as the jquery and native plugins. If you’d like to start using 1.1.0 and maintain existing
functionality, you’ll want to use: http://cdn.ravenjs.com/1.1.0/jquery,native/raven.min.js For a list of other plugins,
checkout http://ravenjs.com
ravenjs.com
A new website dedicated to helping you compile a custom build of raven.js
whitelistUrls
whitelistUrls are recommended over ignoreUrls. whitelistUrls drastically helps cut out noisy error
messages from other scripts running on your site.
3.1. Changelog
17
raven-js Documentation, Release 1.1.16
Misc
• ignoreUrls, ignoreErrors, includePaths have all been unified to accept both a regular expression
and strings to avoid confusion and backwards compatability
• Raven.wrap recursively wraps arguments
• Events are dispatched when an exception is received, recorded or failed sending to Sentry
• Support newer Sentry protocol which allows smaller packets
• Allow loading raven async with RavenConfig
• Entirely new build system with Grunt
• options.collectWindowErrors to tell Raven to ignore window.onerror
18
Chapter 3. What’s New?
CHAPTER 4
Resources
• Download
• Bug Tracker
• Code
• IRC (irc.freenode.net, #sentry)
• Changelog
• Follow @mattrobenolt on Twitter for updates!
19