Raven.js is a lightweight JavaScript client for Sentry, a popular error tracking and performance monitoring platform. It allows you to easily integrate Sentry into your JavaScript applications (both frontend and backend Node.js applications) to capture and monitor errors, exceptions, and other performance issues. Raven.js sends detailed error reports to your Sentry project, providing valuable insights into the stability and performance of your applications. This enables you to proactively identify, diagnose, and resolve issues before they impact your users. Essentially, it acts as a bridge between your application’s JavaScript code and the Sentry platform.
Setting up Raven.js typically involves these steps:
Create a Sentry project: Sign up for a Sentry account and create a new project. You’ll receive a DSN (Data Source Name), a unique identifier for your project that Raven.js will use to send error reports.
Include Raven.js in your project: Include the Raven.js script in your application’s HTML file, preferably before your application’s JavaScript code:
<script src="https://cdn.jsdelivr.net/npm/raven-js@3.26.4/dist/raven.min.js"></script>
Initialize Raven.js: Use the Raven.config()
method to initialize Raven.js with your DSN:
.config('YOUR_DSN_HERE', {
Raven// Optional configuration options
release: '1.0.0', // Your application's version
environment: 'production', // Your application's environment
// ... other options
.install(); })
Replace YOUR_DSN_HERE
with your actual DSN.
Raven.js integrates well with various popular JavaScript frameworks. While the core functionality remains consistent, framework-specific integration might involve additional setup steps or plugins. For example:
For specific integration details with a particular framework, please refer to the official Sentry documentation and any community-contributed plugins or extensions. The key principle remains consistent: initialize Raven.js with your DSN and let it handle error reporting.
The Raven.js error reporting workflow involves several key steps:
Error Capture: When an uncaught exception occurs in your JavaScript application, Raven.js intercepts it. It also captures errors that are explicitly reported using Raven.captureException()
or Raven.captureMessage()
.
Data Collection: Raven.js gathers various data points related to the error, including:
Data Processing: Raven.js processes the collected data, potentially applying source maps to de-minify the code for better readability.
Transmission: The processed error data is sent to your Sentry project using an asynchronous HTTP request. This ensures that the error reporting process doesn’t block your application’s execution.
Reporting and Analysis: Your Sentry project receives the data, allowing you to view error reports, analyze trends, and debug issues.
Raven.js automatically captures unhandled JavaScript exceptions. However, you can also explicitly report exceptions using Raven.captureException()
:
try {
// Some code that might throw an exception
throw new Error("Something went wrong!");
catch (error) {
} .captureException(error);
Raven// Optionally handle the error gracefully in your application
}
This allows for more controlled error reporting, even if you are handling the exception within a try...catch
block. You may want to report the error to Sentry while providing a user-friendly fallback in your application.
Breadcrumbs are a series of contextual events recorded before an error occurs, providing valuable insight into the user’s actions and application state leading up to the crash. Raven.js automatically records some breadcrumbs (e.g., navigation events), but you can manually add your own using Raven.leaveBreadcrumb()
:
.leaveBreadcrumb({
Ravencategory: 'user action',
message: 'User clicked "Submit"',
data: {
formId: 'myForm'
}; })
This helps in understanding the sequence of events that might have contributed to the error.
Contexts provide additional information about the environment and state of your application at the time of the error. You can set contexts using Raven.context()
:
.context({
Ravenuser: {
id: 123,
email: 'user@example.com'
,
}session: {
id: 'abcdef123456'
}, function () {
}// Code that might throw an error
; })
This makes error reports more informative and easier to debug, as they include relevant user and session details.
Tags and extra data provide additional metadata to your error reports. Tags are key-value pairs used for filtering and grouping errors (e.g., environment: 'production'
, version: '1.2.3'
). Extra data is arbitrary key-value data that provides more detailed context for a specific error. You can add them with Raven.setTags()
and Raven.setExtraContext()
:
.setTagsContext({
Ravenenvironment: 'staging',
feature: 'new-payment-system'
;
})
.setExtraContext({
Ravenorder_id: 1234,
payment_method: 'credit card'
; })
Raven.js doesn’t directly handle user feedback mechanisms. However, you can integrate a user feedback system into your application and include that information in the error reports, for example using Raven.setExtraContext()
. This helps enrich your error reports with valuable user insights. You would need to implement a separate feedback mechanism (e.g., a feedback form) to collect user input, and then include that data in the context or extra data passed to Raven.js.
The most basic Raven.js configuration involves initializing the client with your Sentry DSN (Data Source Name). This is typically done by including the Raven.js script and then calling Raven.config()
before any other Raven.js functions:
<script src="https://cdn.jsdelivr.net/npm/raven-js@3.26.4/dist/raven.min.js"></script>
<script>
.config('YOUR_DSN_HERE').install();
Raven</script>
Replace YOUR_DSN_HERE
with your project’s DSN. The install()
method ensures that Raven.js starts capturing errors. This is the minimum setup needed for basic error reporting.
Raven.js offers several advanced configuration options to customize its behavior:
release
: Specifies the version of your application (e.g., ‘1.0.0’). This helps in grouping errors related to specific releases.
environment
: Indicates the environment your application is running in (e.g., ‘development’, ‘staging’, ‘production’). This allows for filtering errors by environment.
sampleRate
: Controls the percentage of errors sent to Sentry. Setting it to a value less than 1.0 (e.g., 0.5) will only send 50% of the errors, useful for reducing load on your Sentry project during development or for high-traffic applications.
whitelistUrls
: An array of regular expressions specifying URLs to include for error reporting. Useful for filtering out errors from specific parts of your application or external scripts.
blacklistUrls
: Similar to whitelistUrls
, but specifies URLs to exclude from error reporting.
ignoreErrors
: An array of strings or regular expressions specifying error messages to ignore. Useful for filtering out known or irrelevant errors.
dataCallback
: A function that allows modification of the error data before it’s sent to Sentry. This is useful for adding custom context or sanitizing sensitive information.
Example with some advanced options:
.config('YOUR_DSN_HERE', {
Ravenrelease: '1.2.3',
environment: 'production',
sampleRate: 0.8,
ignoreErrors: ['Network Error'],
dataCallback: function(data) {
// Modify the data object here
return data;
}.install(); })
Beyond basic configuration, you can customize error reporting using several methods:
Raven.captureException(error)
: Manually capture and send a specific exception.
Raven.captureMessage(message)
: Send a custom error message.
Raven.captureBreadcrumb(breadcrumb)
: Add a custom breadcrumb.
Raven.setExtraContext(data)
: Add extra context to subsequent error reports.
Raven.setTagsContext(tags)
: Set tags for subsequent error reports.
Raven.setUserContext(user)
: Set user context for subsequent error reports. This is useful for associating errors with specific users.
You can configure Raven.js using environment variables. This is particularly useful for setting the DSN and other sensitive information without hardcoding it into your JavaScript code. The specific method for accessing environment variables depends on your deployment environment. For example, you might use process.env.SENTRY_DSN
in a Node.js environment. This value would then be used within the Raven.config()
call.
It’s crucial to sanitize sensitive data before sending it to Sentry. Use the dataCallback
configuration option to filter out potentially sensitive information like passwords, credit card numbers, and personally identifiable information (PII). You can use regular expressions or other data manipulation techniques to remove or replace sensitive data within this callback function. This ensures compliance with privacy regulations and protects sensitive user information. Always prioritize data security and responsible error reporting.
This section focuses on the Sentry side of the configuration, not the Raven.js client-side setup. Raven.js relies on a correctly configured Sentry project to function properly.
Create an Account: Sign up for a Sentry account at sentry.io.
Create a New Project: After logging in, create a new project. Choose a name for your project and select the relevant platform (JavaScript for frontend or Node.js for backend applications using Raven.js).
Obtain Your DSN: Once your project is created, you’ll receive a DSN (Data Source Name). This DSN is a unique identifier for your project and is crucial for connecting Raven.js to your Sentry instance. Treat your DSN as a secret and do not expose it in your client-side code (especially not in publicly accessible files).
Connecting Raven.js to your Sentry project is primarily done by providing your DSN to the Raven.config()
method in your client-side JavaScript code (as detailed in the Client-Side Configuration section). Sentry handles receiving and processing the error data sent by Raven.js. The server-side aspect here is ensuring the Sentry project itself is properly set up to receive and process the data.
Sentry provides tools for managing multiple projects and teams within your organization. You can:
Create multiple projects: Organize your projects based on applications, environments (development, staging, production), or other relevant criteria.
Create teams: Group users into teams to manage access and permissions to specific projects. This allows for better collaboration and control over who can access error reports.
Assign roles: Define roles and permissions for users within teams. This ensures that only authorized personnel can view and manage error data.
These features are managed through the Sentry web interface.
Sentry uses its own authentication system to manage user access. You can invite members to your organization and assign them roles within projects. These roles determine their level of access, such as viewing error reports, managing settings, or performing administrative tasks. This robust authentication system ensures only authorized personnel can access and modify your error data and project settings.
Sentry allows granular control over access to your projects and data. You can:
Restrict access to specific projects: Ensure that only authorized teams or individuals have access to error data from certain projects.
Set permission levels: Define different permission levels for users (e.g., read-only access, full access, administrative access).
Manage user access: Invite, remove, and modify permissions for users associated with your Sentry organization and projects.
This detailed access control helps maintain data security and restricts access to sensitive error information based on user roles and responsibilities. Always configure your Sentry organization and projects to match the security and access control requirements of your development workflow.
While Raven.js offers excellent integration with various frameworks, you might need custom integrations for specific libraries or tools not directly supported. This involves creating custom code to capture errors or events from those libraries and report them to Raven.js using functions like Raven.captureException()
or Raven.captureMessage()
. You’ll need to understand the error handling mechanisms of the library you’re integrating and tailor your code to capture the relevant information and context.
Raven.js’s core functionality can be extended to add features or customize existing behaviors. This might involve creating custom middleware functions that manipulate data before it’s sent to Sentry or implementing custom breadcrumb handlers to capture specific events. The dataCallback
configuration option and the breadcrumb API are key points for achieving this.
Creating plugins for Raven.js allows you to share custom integrations and extensions with others. A plugin would typically be a self-contained module that extends Raven.js’s capabilities, such as adding support for a new framework or integrating with a specific logging system. These plugins would need to adhere to specific conventions to ensure compatibility and seamless integration with Raven.js. Consult the Sentry documentation for guidelines on plugin development.
Troubleshooting Raven.js issues usually involves verifying:
Raven.showReportDialog()
: This method can be used to show Sentry’s error reporting dialog to the user, which can be helpful for collecting additional debugging context.If errors aren’t being reported, carefully review your Raven.js configuration and integration, ensuring it aligns correctly with the project setup within your Sentry dashboard.
While Raven.js is lightweight, optimizing its use can improve performance, especially in high-traffic applications:
sampleRate
: Lowering the sampleRate
reduces the number of error reports sent, decreasing the load on both your application and Sentry.
Asynchronous Operations: Ensure all interactions with Raven.js are asynchronous to avoid blocking the main thread.
Error Filtering: Use the ignoreErrors
option to filter out known, non-critical, or frequently occurring errors.
Minification: Use minified versions of Raven.js to reduce the script’s size.
Caching: Use caching mechanisms to avoid unnecessary network requests.
Balancing the level of error reporting with application performance is crucial; minimizing unnecessary reporting improves the application’s speed and responsiveness without sacrificing valuable diagnostic data. Carefully consider the trade-offs between the amount of data sent and the impact on performance.
This section describes how to use the Sentry dashboard to monitor and analyze error data collected by Raven.js.
The Sentry dashboard provides a central location to view and manage error reports. The overview typically includes:
Sentry allows you to track and manage individual issues effectively:
Sentry offers robust filtering and searching capabilities to easily find specific errors:
Sentry’s charts and graphs help analyze error trends:
Sentry enables you to generate reports to summarize error data:
These reports are valuable for tracking progress, identifying recurring problems, and demonstrating the impact of your bug fixes or performance optimizations. Use the reporting features to create informative summaries of your error data for various audiences, from your development team to management.
This section provides a brief overview of key Raven.js API methods. For the most up-to-date and complete documentation, refer to the official Sentry documentation.
Raven.captureException()
Sends an exception to Sentry. This is typically used within a try...catch
block to report exceptions that are caught by your application’s code.
try {
// Code that might throw an exception
catch (e) {
} .captureException(e);
Raven }
e
: (Error object) The exception to be reported. This should be a JavaScript Error
object or a similar object with a message
and optionally a stack
property.Raven.captureMessage()
Sends a custom message to Sentry. Useful for reporting errors that aren’t necessarily JavaScript exceptions (e.g., network errors or warnings).
.captureMessage('A critical error occurred!'); Raven
message
: (String) The error message to be reported.Raven.captureBreadcrumb()
Manually adds a breadcrumb to the current session’s breadcrumb trail. Breadcrumbs provide context surrounding an error.
.captureBreadcrumb({
Ravenmessage: 'User clicked the submit button',
category: 'ui.action',
data: { buttonId: 'submitBtn' }
; })
breadcrumb
: (Object) An object containing breadcrumb information. Common properties include message
, category
, type
, and data
.Raven.setContext()
Sets contextual information for subsequent error reports. This information will be included in the error report sent to Sentry.
.setContext({
Ravenuser: { id: 123, name: 'John Doe' },
session: { id: 'abcdef' }
; })
context
: (Object) An object containing contextual data.Raven.setUser()
Sets user information for subsequent error reports.
.setUser({
Ravenid: 123,
email: 'john.doe@example.com',
username: 'johndoe'
; })
user
: (Object) An object containing user information (e.g., id
, email
, username
).Raven.showReportDialog()
Displays Sentry’s report dialog, allowing users to submit feedback or additional information about an error.
.showReportDialog({
Raventitle: 'Oops, something went wrong!',
message: 'We are working on fixing this issue. Please submit your feedback to help us improve.'
; })
options
: (Object, optional) Options to customize the dialog (e.g., title
, message
, name
, email
).Raven.js provides other methods for more advanced usage, including:
Raven.uninstall()
: Uninstalls Raven.js, stopping error reporting.Raven.setTagsContext()
: Sets tags for subsequent error reports (used for filtering and grouping errors).Raven.setExtraContext()
: Adds additional key-value pairs of data to subsequent reports.Raven.lastEventId()
: Returns the ID of the last event sent to Sentry.Raven.isSetup()
: Checks if Raven.js is properly configured.Raven.state
: Provides access to Raven.js’s internal state (use with caution). This property allows inspection of the client’s configuration and internal data but should generally only be used for advanced debugging.Refer to the official Sentry documentation for detailed explanations and examples of all available API methods. Always consult the official documentation for the most up-to-date information and examples. The API might change with newer versions of Raven.js.
This guide helps you migrate from older versions of Raven.js to the latest version. Always consult the official Sentry release notes for the most accurate and up-to-date information on breaking changes and migration instructions.
Breaking changes between major versions of Raven.js are infrequent but can occur. These changes might include:
Always check the release notes for the specific version you are upgrading to for a detailed list of breaking changes.
A typical upgrade process involves:
Check for Breaking Changes: Carefully review the release notes for the new version to identify any breaking changes affecting your code.
Update the Raven.js Script: Replace the old Raven.js script in your HTML file with the new version. Use a Content Delivery Network (CDN) or download the updated version from the official Sentry website.
Update Configuration: Adjust your Raven.js configuration (Raven.config()
) to reflect any changes in configuration options. Pay close attention to any renamed or removed options.
Update Code: Modify your code to accommodate any API changes. Rename functions, adjust parameters, or remove deprecated methods as needed.
Testing: Thoroughly test your application after the upgrade to ensure all error reporting functionality works correctly.
Browser Compatibility: Raven.js generally supports modern browsers. Refer to the official documentation for compatibility details. Older browsers might require polyfills for specific features.
Framework Compatibility: Raven.js integrates with many popular frameworks. Check the Sentry documentation for compatibility information regarding the frameworks used in your project. Ensure the new version maintains compatibility with your chosen framework.
Node.js Compatibility: If you use Raven.js in a Node.js environment, check the compatibility notes for the Node.js version you are using. Ensure the required Node.js version aligns with the new Raven.js version.
Migrating to a new major version should be a deliberate process. Consider creating a staging or testing environment to perform the upgrade and thoroughly test the changes before deploying to production. A phased rollout strategy might be prudent for large applications to minimize disruption during the migration.
DSN (Data Source Name): A unique identifier for your Sentry project that Raven.js uses to send error reports. It’s essential for connecting your application to your Sentry instance.
Breadcrumb: A record of an event that occurred before an error, providing context for debugging. Examples include user actions, network requests, and logging events.
Context: Additional information added to error reports to provide more details about the application’s state at the time of the error. This might include user information, session data, or environment variables.
Tag: A key-value pair used to categorize and filter error reports (e.g., environment: production
, feature: login
).
Issue: A grouping of similar error reports in Sentry, often representing a specific bug.
Stack Trace: A list of function calls that led to an error, showing the execution path in your code.
Source Map: A file that maps minified code back to its original source code, making debugging easier.
Sample Rate: A percentage (0.0 to 1.0) that controls how many error reports are sent to Sentry. Lowering it reduces load on Sentry but might also reduce the diagnostic data you collect.
Release: A version identifier for your application, used to group errors from specific releases.
Why aren’t my errors showing up in Sentry? Check your DSN, network connectivity, and the Sentry dashboard for any error messages. Ensure your Raven.js configuration is correct, and review the browser console for any JavaScript errors.
How do I add custom data to my error reports? Use Raven.setContext()
, Raven.setTagsContext()
, and Raven.setExtraContext()
to add custom data.
How can I prevent specific errors from being reported? Use the ignoreErrors
option in the Raven.js configuration to filter out unwanted errors.
What is the difference between captureException()
and captureMessage()
? Use captureException()
for JavaScript exceptions and captureMessage()
for custom error messages.
How can I improve the performance of Raven.js? Lower the sample rate, use asynchronous operations, and filter out unnecessary error reports.
Refer to the “Troubleshooting and Debugging” section in the Advanced Usage chapter for detailed troubleshooting guidance. Common issues include incorrect DSN, network problems, and misconfigurations within the Raven.js initialization. Always check the Sentry dashboard and your browser’s developer console for diagnostic information.
Contributions to Raven.js are welcome! Before contributing, review the contribution guidelines on the Sentry project’s repository. This typically involves:
Contributions usually include bug fixes, new features, and improvements to the documentation. Follow the project’s established style guides and coding conventions when submitting your code. Your contributions will help improve Raven.js and benefit the broader development community.