Class: Bugwatch::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/bugwatch/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



3
4
5
# File 'lib/bugwatch/middleware.rb', line 3

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/bugwatch/middleware.rb', line 7

def call(env)
  if Bugwatch.skip_tracking? || skip_path?(env)
    return @app.call(env)
  end

  start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  BreadcrumbCollector.clear
  UserContext.clear
  ReportedExceptions.clear
  RequestContext.set(env)

  config = Bugwatch.configuration
  collecting = config.enable_db_tracking && (rand < config.db_sample_rate)
  DbTracker.start_request(collecting: collecting)

  collecting_http = config.enable_http_tracking && (rand < config.http_sample_rate)
  HttpTracker.start_request(collecting: collecting_http)

  tracking_rescued = config.enable_rescued_exception_tracking
  RescuedExceptionTracker.start_request if tracking_rescued

  begin
    status, headers, body = @app.call(env)
    report_rescued_exceptions(env) if tracking_rescued
    record_transaction(env, status, start)
    [status, headers, body]
  rescue Exception => e # rubocop:disable Lint/RescueException
    duration_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start) * 1000).round

    begin
      if !Bugwatch.configuration.ignore?(e) && !ReportedExceptions.reported?(e)
        payload = ErrorBuilder.new(e, env).build
        payload[:duration_ms] = duration_ms
        Notification.new(payload).deliver
        ReportedExceptions.mark(e)
      end
    rescue StandardError
      # Never let reporting failures drop the original exception
    end

    record_transaction(env, 500, start)
    raise
  ensure
    RescuedExceptionTracker.clear if tracking_rescued
    RequestContext.clear
    DbTracker.clear
    HttpTracker.clear
  end
end