Raven JS - Documentation

What is Raven.js?

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.

Key Features and Benefits

Setting up Raven.js

Setting up Raven.js typically involves these steps:

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

  2. 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>
  3. Initialize Raven.js: Use the Raven.config() method to initialize Raven.js with your DSN:

    Raven.config('YOUR_DSN_HERE', {
        // 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.

Core Concepts

Error Reporting Workflow

The Raven.js error reporting workflow involves several key steps:

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

  2. Data Collection: Raven.js gathers various data points related to the error, including:

  3. Data Processing: Raven.js processes the collected data, potentially applying source maps to de-minify the code for better readability.

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

  5. Reporting and Analysis: Your Sentry project receives the data, allowing you to view error reports, analyze trends, and debug issues.

Exception Handling

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) {
  Raven.captureException(error);
  // 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():

Raven.leaveBreadcrumb({
  category: '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

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():

Raven.context({
  user: {
    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

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():

Raven.setTagsContext({
  environment: 'staging',
  feature: 'new-payment-system'
});

Raven.setExtraContext({
  order_id: 1234,
  payment_method: 'credit card'
});

User Feedback

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.

Client-Side Configuration

Basic Configuration

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>
  Raven.config('YOUR_DSN_HERE').install();
</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.

Advanced Configuration Options

Raven.js offers several advanced configuration options to customize its behavior:

Example with some advanced options:

Raven.config('YOUR_DSN_HERE', {
  release: '1.2.3',
  environment: 'production',
  sampleRate: 0.8,
  ignoreErrors: ['Network Error'],
  dataCallback: function(data) {
    // Modify the data object here
    return data;
  }
}).install();

Customizing Error Reporting

Beyond basic configuration, you can customize error reporting using several methods:

Environment Variables

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.

Data Sanitization

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.

Server-Side Configuration (Sentry)

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.

Setting up a Sentry Project

  1. Create an Account: Sign up for a Sentry account at sentry.io.

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

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

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.

Managing Projects and Teams

Sentry provides tools for managing multiple projects and teams within your organization. You can:

These features are managed through the Sentry web interface.

User Authentication and Authorization

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.

Access Control

Sentry allows granular control over access to your projects and data. You can:

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.

Advanced Usage

Custom Integrations

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.

Extending Raven.js Functionality

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.

Plugin Development

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

Troubleshooting Raven.js issues usually involves verifying:

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.

Performance Optimization

While Raven.js is lightweight, optimizing its use can improve performance, especially in high-traffic applications:

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.

Monitoring and Analysis

This section describes how to use the Sentry dashboard to monitor and analyze error data collected by Raven.js.

Dashboard Overview

The Sentry dashboard provides a central location to view and manage error reports. The overview typically includes:

Issue Tracking and Management

Sentry allows you to track and manage individual issues effectively:

Filtering and Searching

Sentry offers robust filtering and searching capabilities to easily find specific errors:

Sentry’s charts and graphs help analyze error trends:

Generating Reports

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.

API Reference

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) {
  Raven.captureException(e);
}

Raven.captureMessage()

Sends a custom message to Sentry. Useful for reporting errors that aren’t necessarily JavaScript exceptions (e.g., network errors or warnings).

Raven.captureMessage('A critical error occurred!');

Raven.captureBreadcrumb()

Manually adds a breadcrumb to the current session’s breadcrumb trail. Breadcrumbs provide context surrounding an error.

Raven.captureBreadcrumb({
  message: 'User clicked the submit button',
  category: 'ui.action',
  data: { buttonId: 'submitBtn' }
});

Raven.setContext()

Sets contextual information for subsequent error reports. This information will be included in the error report sent to Sentry.

Raven.setContext({
  user: { id: 123, name: 'John Doe' },
  session: { id: 'abcdef' }
});

Raven.setUser()

Sets user information for subsequent error reports.

Raven.setUser({
  id: 123,
  email: 'john.doe@example.com',
  username: 'johndoe'
});

Raven.showReportDialog()

Displays Sentry’s report dialog, allowing users to submit feedback or additional information about an error.

Raven.showReportDialog({
  title: 'Oops, something went wrong!',
  message: 'We are working on fixing this issue.  Please submit your feedback to help us improve.'
});

Other API methods

Raven.js provides other methods for more advanced usage, including:

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.

Migration Guide (from previous versions)

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

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.

Upgrade Instructions

A typical upgrade process involves:

  1. Check for Breaking Changes: Carefully review the release notes for the new version to identify any breaking changes affecting your code.

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

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

  4. Update Code: Modify your code to accommodate any API changes. Rename functions, adjust parameters, or remove deprecated methods as needed.

  5. Testing: Thoroughly test your application after the upgrade to ensure all error reporting functionality works correctly.

Compatibility Notes

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.

Appendix

Glossary of Terms

FAQ

Troubleshooting

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.

Contributing to Raven.js

Contributions to Raven.js are welcome! Before contributing, review the contribution guidelines on the Sentry project’s repository. This typically involves:

  1. Forking the Repository: Create a fork of the Raven.js repository on GitHub.
  2. Creating a Branch: Create a new branch for your changes.
  3. Making Changes: Implement your changes and write tests to ensure your modifications work correctly.
  4. Submitting a Pull Request: Create a pull request to merge your changes into the main repository.

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.