Git Product home page Git Product logo

airbrake-js's Introduction

Airbrake

Build Status Code Climate Gem Version Documentation Status Downloads Reviewed by Hound

Introduction

Airbrake is an online tool that provides robust exception tracking in any of your Ruby applications. In doing so, it allows you to easily review errors, tie an error to an individual piece of code, and trace the cause back to recent changes. The Airbrake dashboard provides easy categorization, searching, and prioritization of exceptions so that when errors occur, your team can quickly determine the root cause.

Key features

The Airbrake Dashboard

This library is built on top of Airbrake Ruby. The difference between Airbrake and Airbrake Ruby is that the airbrake gem is just a collection of integrations with frameworks or other libraries. The airbrake-ruby gem is the core library that performs exception sending and other heavy lifting.

Normally, you just need to depend on this gem, select the integration you are interested in and follow the instructions for it. If you develop a pure frameworkless Ruby application or embed Ruby and don't need any of the listed integrations, you can depend on the airbrake-ruby gem and ignore this gem entirely.

The list of integrations that are available in this gem includes:

Deployment tracking:

Installation

Bundler

Add the Airbrake gem to your Gemfile:

gem 'airbrake'

Manual

Invoke the following command from your terminal:

gem install airbrake

Configuration

Rails

Integration

To integrate Airbrake with your Rails application, you need to know your project id and project key. Set AIRBRAKE_PROJECT_ID & AIRBRAKE_PROJECT_KEY environment variables with your project's values and generate the Airbrake config:

export AIRBRAKE_PROJECT_ID=<PROJECT ID>
export AIRBRAKE_PROJECT_KEY=<PROJECT KEY>

rails g airbrake

Heroku add-on users can omit specifying the key and the id. Heroku add-on's environment variables will be used (Heroku add-on docs):

rails g airbrake

This command will generate the Airbrake configuration file under config/initializers/airbrake.rb. Make sure that this file is checked into your version control system. This is enough to start Airbraking.

In order to configure the library according to your needs, open up the file and edit it. The full list of supported configuration options is available online.

To test the integration, invoke a special Rake task that we provide:

rake airbrake:test

In case of success, a test exception should appear in your dashboard.

The notify_airbrake controller helpers

The Airbrake gem defines two helper methods available inside Rails controllers: #notify_airbrake and #notify_airbrake_sync. If you want to notify Airbrake from your controllers manually, it's usually a good idea to prefer them over Airbrake.notify, because they automatically add information from the Rack environment to notices. #notify_airbrake is asynchronous, while #notify_airbrake_sync is synchronous (waits for responses from the server and returns them). The list of accepted arguments is identical to Airbrake.notify.

Additional features: user reporting, sophisticated API

The library sends all uncaught exceptions automatically, attaching the maximum possible amount information that can help you to debug errors. The Airbrake gem is capable of reporting information about the currently logged in user (id, email, username, etc.), if you use an authentication library such as Devise. The library also provides a special API for manual error reporting. The description of the API is available online.

Automatic integration with Rake tasks and Rails runner

Additionally, the Rails integration offers automatic exception reporting in any Rake tasks[link] and Rails runner.

Integration with filter_parameters

If you want to reuse Rails.application.config.filter_parameters in Airbrake you can configure your notifier the following way:

# config/initializers/airbrake.rb
Airbrake.configure do |c|
  c.blocklist_keys = Rails.application.config.filter_parameters
end

There are a few important details:

  1. You must load filter_parameter_logging.rb before the Airbrake config
  2. If you use Lambdas to configure filter_parameters, you need to convert them to Procs. Otherwise you will get ArgumentError
  3. If you use Procs to configure filter_parameters, the procs must return an Array of keys compatible with the Airbrake allowlist/blocklist option (String, Symbol, Regexp)

Consult the example application, which was created to show how to configure filter_parameters.

filter_parameters dot notation warning

The dot notation introduced in rails/pull/13897 for filter_parameters (e.g. a key like credit_card.code) is unsupported for performance reasons. Instead, simply specify the code key. If you have a strong opinion on this, leave a comment in the dedicated issue.

Logging

In new Rails apps, by default, all the Airbrake logs are written into log/airbrake.log. In older versions we used to write to wherever Rails.logger writes. If you wish to upgrade your app to the new behaviour, please configure your logger the following way:

c.logger = Airbrake::Rails.logger

Sinatra

To use Airbrake with Sinatra, simply require the gem, configure it and use our Rack middleware.

# myapp.rb
require 'sinatra/base'
require 'airbrake'

Airbrake.configure do |c|
  c.project_id = 113743
  c.project_key = 'fd04e13d806a90f96614ad8e529b2822'

  # Display debug output.
  c.logger.level = Logger::DEBUG
end

class MyApp < Sinatra::Base
  use Airbrake::Rack::Middleware

  get('/') { 1/0 }
end

run MyApp.run!

To run the app, add a file called config.ru to the same directory and invoke rackup from your console.

# config.ru
require_relative 'myapp'

That's all! Now you can send a test request to localhost:9292 and check your project's dashboard for a new error.

curl localhost:9292

Rack

To send exceptions to Airbrake from any Rack application, simply use our Rack middleware, and configure the notifier.

require 'airbrake'
require 'airbrake/rack'

Airbrake.configure do |c|
  c.project_id = 113743
  c.project_key = 'fd04e13d806a90f96614ad8e529b2822'
end

use Airbrake::Rack::Middleware

Note: be aware that by default the library doesn't filter any parameters, including user passwords. To filter out passwords add a filter.

Appending information from Rack requests

If you want to append additional information from web requests (such as HTTP headers), define a special filter such as:

Airbrake.add_filter do |notice|
  next unless (request = notice.stash[:rack_request])
  notice[:params][:remoteIp] = request.env['REMOTE_IP']
end

The notice object carries a real Rack::Request object in its stash. Rack requests will always be accessible through the :rack_request stash key.

Optional Rack request filters

The library comes with optional predefined builders listed below.

RequestBodyFilter

RequestBodyFilter appends Rack request body to the notice. It accepts a length argument, which tells the filter how many bytes to read from the body.

By default, up to 4096 bytes is read:

Airbrake.add_filter(Airbrake::Rack::RequestBodyFilter.new)

You can redefine how many bytes to read by passing an Integer argument to the filter. For example, read up to 512 bytes:

Airbrake.add_filter(Airbrake::Rack::RequestBodyFilter.new(512))

Sending custom route breakdown performance

Arbitrary code performance instrumentation

For every route in your app Airbrake collects performance breakdown statistics. If you need to monitor a specific operation, you can capture your own breakdown:

def index
  Airbrake::Rack.capture_timing('operation name') do
    call_operation(...)
  end

  call_other_operation
end

That will benchmark call_operation and send performance information to Airbrake, to the corresponding route (under the 'operation name' label).

Method performance instrumentation

Alternatively, you can measure performance of a specific method:

class UsersController
  extend Airbrake::Rack::Instrumentable

  def index
    call_operation(...)
  end
  airbrake_capture_timing :index
end

Similarly to the previous example, performance information of the index method will be sent to Airbrake.

Sidekiq

We support Sidekiq v2+. The configurations steps for them are identical. Simply require our integration and you're done:

require 'airbrake/sidekiq'

If you required Sidekiq before Airbrake, then you don't even have to require anything manually and it should just work out-of-box.

Airbrake::Sidekiq::RetryableJobsFilter

By default, Airbrake notifies of all errors, including reoccurring errors during a retry attempt. To filter out these errors and only get notified when Sidekiq has exhausted its retries you can add the RetryableJobsFilter:

Airbrake.add_filter(Airbrake::Sidekiq::RetryableJobsFilter.new)

The filter accepts an optional max_retries parameter. When set, it configures the amount of allowed job retries that won't trigger an Airbrake notification. Normally, this parameter is configured by the job itself but this setting takes the highest precedence and forces the value upon all jobs, so be careful when you use it. By default, it's not set.

Airbrake.add_filter(
  Airbrake::Sidekiq::RetryableJobsFilter.new(max_retries: 10)
)

ActiveJob

No additional configuration is needed. Simply ensure that you have configured your Airbrake notifier with your queue adapter.

Resque

Simply require the Resque integration:

require 'airbrake/resque'

Integrating with Rails applications

If you're working with Resque in the context of a Rails application, create a new initializer in config/initializers/resque.rb with the following content:

# config/initializers/resque.rb
require 'airbrake/resque'
Resque::Failure.backend = Resque::Failure::Airbrake

Now you're all set.

General integration

Any Ruby app using Resque can be integrated with Airbrake. If you can require the Airbrake gem after Resque, then there's no need to require airbrake/resque anymore:

require 'resque'
require 'airbrake'

Resque::Failure.backend = Resque::Failure::Airbrake

If you're unsure, just configure it similar to the Rails approach. If you use multiple backends, then continue reading the needed configuration steps in the Resque wiki (it's fairly straightforward).

DelayedJob

Simply require our integration and you're done:

require 'airbrake/delayed_job'

If you required DelayedJob before Airbrake, then you don't even have to require anything manually and it should just work out-of-box.

Shoryuken

Simply require our integration and you're done:

require 'airbrake/shoryuken'

If you required Shoryuken before Airbrake, then you don't even have to require anything manually and it should just work out-of-box.

Sneakers

Simply require our integration and you're done:

require 'airbrake/sneakers'

If you required Sneakers before Airbrake, then you don't even have to require anything manually and it should just work out-of-box.

ActionCable

The ActionCable integration sends errors occurring in ActionCable actions and subscribed/unsubscribed events. If you use Rails with ActionCable, there's nothing to do, it's already loaded. If you use ActionCable outside Rails, simply require it:

require 'airbrake/rails/action_cable'

Rake

Airbrake offers Rake tasks integration, which is used by our Rails integration[link]. To integrate Airbrake in any project, just require the gem in your Rakefile, if it hasn't been required and configure the notifier.

# Rakefile
require 'airbrake'

Airbrake.configure do |c|
  c.project_id = 113743
  c.project_key = 'fd04e13d806a90f96614ad8e529b2822'
end

task :foo do
  1/0
end

Logger

If you want to convert your log messages to Airbrake errors, you can use our integration with Ruby's Logger class from stdlib. All you need to do is to wrap your logger in Airbrake's decorator class:

require 'airbrake/logger'

# Create a normal logger
logger = Logger.new($stdout)

# Wrap it
logger = Airbrake::AirbrakeLogger.new(logger)

Now you can use the logger object exactly the same way you use it. For example, calling fatal on it will both log your message and send it to the Airbrake dashboard:

logger.fatal('oops')

The Logger class will attempt to utilize the default Airbrake notifier to deliver messages. It's possible to redefine it via #airbrake_notifier:

# Assign your own notifier.
logger.airbrake_notifier = Airbrake::NoticeNotifier.new

Airbrake severity level

In order to reduce the noise from the Logger integration it's possible to configure Airbrake severity level. For example, if you want to send only fatal messages from Logger, then configure it as follows:

# Send only fatal messages to Airbrake, ignore anything below this level.
logger.airbrake_level = Logger::FATAL

By default, airbrake_level is set to Logger::WARN, which means it sends warnings, errors and fatal error messages to Airbrake.

Configuring Airbrake logger integration with a Rails application

In order to configure a production logger with Airbrake integration, simply overwrite Rails.logger with a wrapped logger in an after_initialize callback:

# config/environments/production.rb
config.after_initialize do
  # Standard logger with Airbrake integration:
  # https://github.com/airbrake/airbrake#logger
  Rails.logger = Airbrake::AirbrakeLogger.new(Rails.logger)
end

Configuring Rails APM SQL query stats when using Rails engines

By default, the library collects Rails SQL performance stats. For standard Rails apps no extra configuration is needed. However if your app uses Rails engines, you need to take an additional step to make sure that the file and line information is present for queries being executed in the engine code.

Specifically, you need to make sure that your Rails.backtrace_cleaner has a silencer that doesn't silence engine code (will be silenced by default). For example, if your engine is called blorgh and its main directory is in the root of your project, you need to extend the default silencer provided with Rails and add the path to your engine:

# config/initializers/backtrace_silencers.rb

# Delete default silencer(s).
Rails.backtrace_cleaner.remove_silencers!

# Define custom silencer, which adds support for the "blorgh" engine
Rails.backtrace_cleaner.add_silencer do |line|
  app_dirs_pattern = %r{\A/?(app|config|lib|test|blorgh|\(\w*\))}
  !app_dirs_pattern.match?(line)
end

Plain Ruby scripts

Airbrake supports any type of Ruby applications including plain Ruby scripts. If you want to integrate your script with Airbrake, you don't have to use this gem. The Airbrake Ruby gem provides all the needed tooling.

Deploy tracking

By notifying Airbrake of your application deployments, all errors are resolved when a deploy occurs, so that you'll be notified again about any errors that reoccur after a deployment. Additionally, it's possible to review the errors in Airbrake that occurred before and after a deploy.

There are several ways to integrate deployment tracking with your application, that are described below.

Capistrano

The library supports Capistrano v2 and Capistrano v3. In order to configure deploy tracking with Capistrano simply require our integration from your Capfile:

# Capfile
require 'airbrake/capistrano'

If you use Capistrano 3, define the after :finished hook, which executes the deploy notification task (Capistrano 2 doesn't require this step).

# config/deploy.rb
namespace :deploy do
  after :finished, 'airbrake:deploy'
end

If you version your application, you can set the :app_version variable in config/deploy.rb, so that information will be attached to your deploy.

# config/deploy.rb
set :app_version, '1.2.3'

Rake task

A Rake task can accept several arguments shown in the table below:

Key Required Default Example
ENVIRONMENT No Rails.env production
USERNAME No nil john
REPOSITORY No nil https://github.com/airbrake/airbrake
REVISION No nil 38748467ea579e7ae64f7815452307c9d05e05c5
VERSION No nil v2.0

In Rails

Simply invoke rake airbrake:deploy and pass needed arguments:

rake airbrake:deploy USERNAME=john ENVIRONMENT=production REVISION=38748467 REPOSITORY=https://github.com/airbrake/airbrake

Anywhere

Make sure to require the library Rake integration in your Rakefile.

# Rakefile
require 'airbrake/rake/tasks'

Then, invoke it like shown in the example for Rails.

Supported Rubies

  • CRuby >= 2.6.0
  • JRuby >= 9k

Contact

In case you have a problem, question or a bug report, feel free to:

License

The project uses the MIT License. See LICENSE.md for details.

Development & testing

In order to run the test suite, first of all, clone the repo, and install dependencies with Bundler.

git clone https://github.com/airbrake/airbrake.git
cd airbrake
bundle

Next, run unit tests.

bundle exec rake

In order to test integrations with frameworks and other libraries, install their dependencies with help of the following command:

bundle exec appraisal install

To run integration tests for a specific framework, use the appraisal command.

bundle exec appraisal rails-4.2 rake spec:integration:rails
bundle exec appraisal sinatra rake spec:integration:sinatra

Pro tip: GitHub Actions config has the list of all the integration tests and commands to invoke them.

airbrake-js's People

Contributors

3mroshdy avatar alexcastillo avatar anmic avatar benarent avatar callumacrae avatar charle692 avatar dependabot-preview[bot] avatar dependabot[bot] avatar duncanbeevers avatar eur00t avatar hajder avatar itolmach avatar kole avatar kyrylo avatar lessless avatar mmcdaris avatar odlp avatar ptolemybarnes avatar randomseeded avatar ratbeard avatar rostber avatar seuros avatar sgray avatar shifi avatar shime avatar shinnn avatar thompiler avatar thunberg087 avatar vmihailenco avatar zefer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

airbrake-js's Issues

Option to console.log errors

In some debug cases we'd like to log errors out via console.log (when supported by the browser). If we just let the error get thrown, we would get this info in our console, with Airbrake it's currently hard to find. You could just have a property debugLogErrors which, if set to true, logs errors in this format:

Error: 'options' is undefined
Stack trace: doSomething(), page.js, line 40,
              doSomethingElse(), page.js, line 48,
              rootCauseMethod(), other.js, line 744

Load Airbrake JS async

Customer feedback - I would try something like what GA does, have an onerror that simply tacks stuff in a queue and then the AB codes empties the error queue the whole time. That means we can have the onerror handler directly in the , and only load the AB JS later. For 1st world internet users this might not make sense, but down here in Africa we often spend time waiting on 'api.airbrake.io', and it would just be worse over mobile networks.

Key security vulnerability

Currently the API key is set via function call on a page: window.Airbrake.setKey('703c5fce534...');
The issue is: the key is publicly available and can be used for evil >:-E by any page visitor.

Is this something that should be regarded as critical?

data-airbrake-onload not working

Hello, I tried to use this code :

<script data-airbrake-onload="initAirbrake"> function initAirbrake() { Airbrake.addSession({ split_test: 10 }); } </script>

And it never execute my function ! Does anyone already use it?

Show error title in the console?

One is to be able to view the error in web-inspector so instead of just seeing something like this:

airbrake: error #1099333485350590136 was reported: https://airbrake.io/locate/1099333485350590136

I would also like to see the error appear in the chrome / firefox console.

environment, params and session not sent in 0.3.4

Hi,

We are using Airbrake js from quite a good amount of time and we noticed, after March 6th that the environment, params and session objects are not included in the POST request of an Airbrake.push().

I've setup a jsfiddle that explain the problem here: http://jsfiddle.net/839pw/2/ . I've removed our project-id and key for security purposes.

When the above code is run you can see in the post request the mentioned parameters are missed.

airbrakeerror

JS notifier, Cross origin resource sharing and https issues

I have several issues using the javascript notifier with an https website.

Firstly, it seems api.airbrake.io does not support CORS. The notifier, when creating an xmlhttprequest on a chrome or firefox browser (up-to-date version), tries to do a preflight when POSTing, and thus sends an OPTIONS query, which fails. Here is the console output:

The page at https://[snip]/ displayed insecure content from http://api.airbrake.io/notifier_api/v2/notices.
OPTIONS http://api.airbrake.io/notifier_api/v2/notices 422 (status code 422) notifier.min.js:1
XMLHttpRequest cannot load http://api.airbrake.io/notifier_api/v2/notices. Origin https://[snip] is not allowed by Access-Control-Allow-Origin.

It seems an Access-Control-Allow-Origin header is missing, along with accepting OPTIONS queries, in order to fully support javascript xmlhttprequests.

So in a second attempt, after examining the source code of the notifier, I tried to change the request method to GET by calling Airbrake.setRequestType("GET"). It is indeed a working workaround, but since the http:// protocol prefix is hardcoded, my browser is not too happy about this https/http mixing and displays warnings.

Is there an upcoming version which takes care of these issues? Did I misconfigured something?

Thank you for your answers.

PS: Here is my embedded code:

<script src='//ssljscdn.airbrake.io/notifier.min.js' type='text/javascript'></script>
<script>
  //<![CDATA[
    window.Airbrake = (typeof(Airbrake) == 'undefined' && typeof(Hoptoad) != 'undefined') ? Hoptoad : Airbrake
    // Airbrake.setRequestType("GET");
    Airbrake.setKey("[snip]");
    Airbrake.setHost("api.airbrake.io");
    Airbrake.setEnvironment("development");
    Airbrake.setErrorDefaults({
        url: location.toString(),
        component: "main",
        action: "index"
    });
    Airbrake.setGuessFunctionName(true);
    Airbrake.trackJQ(true);
  //]]>
</script>

cdn for airbrake notifier js

Hi,
We are a JS app and we have decided to use the airbrake-js for our error notifications. I was following the docs and it seems like the cdn source location for notifier.js [<script defer src="https://ssljscdn.airbrake.io/notifier-v0.2.js" ] is incorrect.

<script>
  window.Airbrake = [];
  window.Airbrake.try = function(fn) { try { fn() } catch(er) { window.Airbrake.push(er); } };
</script>
<script defer src="https://ssljscdn.airbrake.io/notifier-v0.2.js"  
        data-airbrake-project-id="1234"
        data-airbrake-project-key="abcd"
        data-airbrake-project-environment-name="production"></script>

Can you let us know what the right cdn is ? Thanks

'Airbrake' is undefined in IEs

Hi guys,

I have a rails app and had some issues with the airbrake_javascript_notifier and decided to try the asynch version. Now everything works fine in all browsers but for IEs where I get the Airbrake is undefined issue.

I also receive a warning in Chrome about insecure content (The page at about:blank displayed insecure content from http://api.airbrake.io/notifier_api/v2/notices?) . I access airbrake with SSL al the time.

Here's my code:

:javascript
  (function(callback) {
    var ab = document.createElement('script');
    ab.type = 'text/javascript'; ab.async = true;
    ab.onload = ab.onreadystatechange = callback;    
    ab.src = "https://ssljscdn.airbrake.io/notifier.min.js";
    var p = document.getElementsByTagName('script')[0];
    p.parentNode.insertBefore(ab, p);
  }(function () {
    Airbrake.setRequestType('GET');
    Airbrake.setGuessFunctionName(false);
    Airbrake.setKey('#{Airbrake.configuration.api_key}');
    Airbrake.setEnvironment('#{Rails.env}');
    Airbrake.setErrorDefaults({
      url: document.URL,
      component: "#{controller_name}",
      action: "#{action_name}",
    });
  }));

Thank you !

Gracefully fail if there is a network issue.

As per on support

The javascript tracker is not available, the host does not resolve.

This causes the browser to stall and show it as indefinitely loading. This affects all the traffic to my site.

https://ssljscdn.airbrake.io/0.3/airbrake.min.js

What can I do to prevent this in case this happens again?

Not capturing data-airbrake-environment

Looks like we are not capturing environment information and also context and session information. It will be good to atleast capture the environment info so that in the airbrake UI we can filter by environment.

Thanks!

Dependencies

After carefully reviewing the docs, it looks like there are no dependencies for the airbrake shim. However, one could easily assume there is a jquery dependency based on the example code shown. Maybe update the docs to reflect that there are no dependencies?

Error page with blank details

I use the Javascript API (https://ssljscdn.airbrake.io/0.3/airbrake.min.js).

By clicking on the link in the error email or by selecting the error from the project error list page I see no details in the main panel. This happens for most of the errors I have for my project.

Here is the piece of code I use:

Airbrake.push({
    error: { name: <string>, message: <string> },
    context: {
        logType: <string>
    },
    environment: <string>,
    params: { url: <string> },
    session: { id: <string> }
});

Annotating Errors not working

Hi i am using this snipped to log an error:

Airbrake.push({
      error: exception,
      context: { backbone_controller: 'style' },
      env:     { navigator_vendor: window.navigator.vendor },
      params:  { search: "foo" },
      session: { username: "john" }
    });

but context, env, params and session do not appear in the airbrake userinterface. am i missing something?

Project_id and project_key.. are not set on error report

Hello,

I am trying to use this script to catch javascript error on my rails application. I configured it like this :

:javascript
    window.Airbrake = [];
    window.Airbrake.try = function(fn) { try { fn() } catch(er) { window.Airbrake.push(er); } };
    %script{ "defer" => "", "src" => "https://ssljscdn.airbrake.io/airbrake-js-tracekit-sourcemap.js", "data-airbrake-project-id" => "92691", "data-airbrake-project-key" => "4a662a0c82ca9210994173a1048d7023", "data-airbrake-project-environment-name" => "production" }

Right after the tag. And when an error is catched, it send to the url :
https://api.airbrake.io/api/v3/projects/undefined/create-notice?key=undefin…2env%22%3A%7B%7D%2C%22params%22%3A%7B%7D%2C%22session%22%3A%7B%7D%7D%5D%7D

As you can see, the project_id is not find. It's due to this part of code :

function JsonpReporter(project_id, project_key, environment_name, processor_name, custom_context_data, custom_environment_data, custom_session_data, custom_params_data) {
  this.report = function(error_data) {
    var output_data = ReportBuilder.build(environment_name, processor_name, custom_context_data, custom_environment_data, custom_session_data, custom_params_data, error_data),
        document    = global.document,
        head        = document.getElementsByTagName("head")[0],
        script_tag  = document.createElement("script"),
        body        = JSON.stringify(output_data),
        cb_name     = "airbrake_cb_" + cb_count,
        prefix      = "https://api.airbrake.io", 
        url         = prefix + "/api/v3/projects/" + project_id + "/create-notice?key=" + project_key + "&callback=" + cb_name + "&body=" + encodeURIComponent(body);


    // Attach an anonymous function to the global namespace to consume the callback.
    // This pevents syntax errors from trying to directly execute the JSON response.
    global[cb_name] = function() { delete global[cb_name]; };
    cb_count += 1;

    function removeTag() { head.removeChild(script_tag); }

    script_tag.src     = url;
    script_tag.type    = "text/javascript";
    script_tag.onload  = removeTag;
    script_tag.onerror = removeTag;

    head.appendChild(script_tag);
  };
}

When it export this function, project_id is undefined. In fact, this export is executed before this :

(function(global){module.exports = function(client) {
  var scripts = global.document.getElementsByTagName("script"),
      i = 0, len = scripts.length, script,
      project_id,
      project_key,
      project_environment_name;

  for (; i < len; i++) {
    script = scripts[i];
    project_id = script.getAttribute("data-airbrake-project-id");
    project_key = script.getAttribute("data-airbrake-project-key");
    project_environment_name = script.getAttribute("data-airbrake-project-environment-name");
    if (project_id && project_key) {
      client.setProject(project_id, project_key);
    }
    if (project_environment_name) {
      client.setEnvironmentName(project_environment_name);
    }
  }
};

So, the project_id is not defined. I used this code to understand what is happening : https://ssljscdn.airbrake.io/airbrake-js-tracekit-sourcemap.js

Asynchronous library code load.

What about making library code download asynchronous? This will save some milliseconds on initial page load. This can be considered as an alternative option in addition to traditional <script src="..."></script> include.

It requires some back-end customization to handle configurable parameters in URL.

https://gist.github.com/b3a33c408c0cd4195b58

Source map support

This is what I see when trying to use source maps with official jQuery CDN:

XMLHttpRequest cannot load http://code.jquery.com/jquery-2.0.3.min.js. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. jquery-example.html:12
XMLHttpRequest cannot load http://code.jquery.com/jquery-2.0.3.min.map. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

I.e. Access-Control-Allow-Origin is not set for jQuery CDN. Google CDN demonstrates the same behaviour.

So the question is: why we bother with client-side source maps support if it does not work with CDNs?

Request type option is ignored

There is a requestType option, but the code ignores it: XML is always send with GET while JSON is always send with POST.

Ability to initialise using Javascript?

Hi, we're writing a website plugin and wondering if it's possible (or sensible) to track our own client-side errors on the clients' website through Airbrake.
Our plugin initialises at the head of the page, assesses the page, and adds event listeners to the window on DOMContentLoaded (so we'd need it to be available before load if possible).
Is it just a case of synchronously AJAXing the script portions in before we do any real work and making them execute?

Update Changelog

@vmihailenco Can you give me instructions on how to update the change-log so I can share in other communications on how to use the notifier.

Custom parameters?

Hi,

I've been struggling to find information about how so send custom data to Airbrake. I've read when exposing current_user, it should be picked up as part of the report. But I've not seen examples of how to send arbitrary data and whether this would be presented in the error report.

Looking at this JSON https://gist.github.com/6957bb7858ddd8b00f4b would adding data to context, session or params be visible in the report? If so, adding a method to populate these from the JS-lib should be trivial but I've yet to be able to test the new JSON api successfully as none of the errors I trigger show up in my test project.

Which plan is needed

Hey, I'm trying to use this module but getting Authorized with the pre-flight Options call. Current plan is Small. Which plan is needed?

Issue with IE

The airbrake JS client is producing errors for me in IE:

The value of the property 'removeScript' is null or undefined, not a Function object
and:

Script error.

Also when navigating to the page the IE shows script errors in the bottom toolbar.

Could you take a look at this? Thank you!

Notice was rejected: either error type or error message is required

H,i I'm getting this response from airbrake-js "Notice was rejected: either error type or error message is required." I contacted airbrake support and was asked to open up an issue.

Code Sample

I was attempting to throw an error when an ajax call failed. I've tried it with ajax error

$.ajax
    url: '/path'
    dataType: 'json'
    cache: false
    success: (data)->
      items = _.map data.items, (itemJSON)->
        itemJSON.item
    error: (jqXhr, textStatus, er)->
      if er
        Airbrake.push({
          error: er
        })

and using .fail()

$.ajax({
    url: '/path'
    dataType: 'json'
    cache: false
    success: (data)->
      items = _.map data.items, (itemJSON)->
        itemJSON.item
    })
    .fail( (jqXhr, textStatus, er)->
      if er
        Airbrake.push({
          error: er
        })
    )

The response from airbrake

airbrake_cb_0({"id":"1058143722744619642","url":"https://airbrake.io/locate/1058143722744619642"}).  

If you go to the url it says "Notice 1058143722744619642 was rejected: either error type or error message is required".

When I console.log(er) right before the Airbrake.push, the output says "Internal Server Error ." For some reason though, it says I'm not passing in an error.

The regular try/catch airbrake works. I'm just having issues with getting airbrakes to trigger in the fail section of an ajax call.

Fix phantomjs

Please add a LICENSE

Is this code MIT licensed, or will it use a similar license to the airbrake gem? (See: https://github.com/airbrake/airbrake/blob/master/LICENSE)

I'm asking because I need to slightly modify the onerror handler to ignore errors that don't come from within our scripts. (If the file doesn't include /assets). Do I have permission to use a modified version of notifier.js?

Use TraceKit for JS stack traces

Customer feedback - Consider using/contributing to the TraceKit project for JS stack traces. We uglify, minify, torture and god knows what else to our JS which makes normal stack traces useless. TraceKit's ability to find the column number will be a huge help in actually making the stack traces somewhat useful.

Caller can pass in an object of custom data in lieu of the handler

In your example code that reports exceptions thrown in jQuery event handlers. I'm getting errors because some triggered events receive objects instead of functions.

If you look at jQuery.event.add you will see code there is reference to this.

Look for a comment that says near the beginning on the function that says: Caller can pass in an object of custom data in lieu of the handler.

Unable to build a new airbrake-js dist

Hi,
I followed the commands mentioned in doc/Developers.mdown file. I am new to using grunt and bower but I followed the instructions. It generated all these files

  • airbrake-js-fallback.js (and sourcemap and min ) version
  • airbrake-js-tracekit.js ( and sourcemap and vim) version.

However I was unable to generated airbrake-js version at all. I am using Mac 10.8.4 and using node version 0.10 and npm version 1.3.2. I installed grunt version 0.4.1.

I just need a copy of the latest working copy of airbrake js. Am I doing this correctly or is there an easier way to get the file ?

Notified of JS Error caused by user using bookmarklet script

Asked to post this here by the support team.


One of our users appears to be using a website's js bookmark widget to share content from our site (a good thing). However, the airbrake js error tracking gets triggered every time.

The bookmarklet seems to work despite this error, but I didn't dig in enough to determine if this is potentially a false positive.

Wether or not this is a "real" JS error, the bookmarklet is outside of our control, and we'd like the ability to filter these out of our notifications if possible.

A typical error looks like this (and seems to be caused by: http://tapiture.com/partners/install-button):

An error has just occurred. View full details at:
https://SUBDOMAIN.airbrake.io/groups/ID_NUMBER
Error Message:
Script error.

Where:
shop#index
http, line 0

URL:
https://www.example.com/
Backtrace:
http://static.tapcdn.com/mosaic/tap_browser.js?ver=0.11640645691864837:0:in `{anonymous}()'

Ignore list

The filtering your Rails client provides is pretty handy, it would be nice to have here also for all those pesky "Script error."s and such.

throw "foobar" is not handled properly

I expect code like this

try {
  throw "foobar";
} catch (exc) {
  Airbrake.capture(exc);
}

to report something meaningful. Currently notifier sends empty error message.

/s/javascripit/javascript

Hello,

Just wanted to let you know that the project's description and README mispell Javascript a few times.

Thanks!

Issue with notifier onload

I want to setup a filter when Airbrake loads. I have the following setup:

<script src="//code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script data-airbrake-environment-name="production" data-airbrake-project-id="xxx" data-airbrake-project-key="xxx" src="/assets/airbrake-shim.js" type="text/javascript"></script>
<script data-airbrake-onload="initAirbrake">
function initAirbrake() {
  Airbrake.addFilter(function (notice) {
    // filter code
  });
}
</script>

This results in:

Uncaught TypeError: Object [object Array] has no method 'addFilter' 

Is there something in this setup I am doing wrong here? I have a workaround but it's far from ideal compared to the above (if it worked):

var interval = 100;
    window.setTimeout(function () {
        if(Airbrake['addFilter']) {
            Airbrake.addFilter(function (notice) {
                // filter code
            });
        } else {
            window.setTimeout(arguments.callee, interval);
        }
    }, interval);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.