Class: OpenTrace::ErrorSubscriber

Inherits:
Object
  • Object
show all
Defined in:
lib/opentrace/error_subscriber.rb

Overview

Rails 7.0+ Error Reporter subscriber.

Captures ALL exceptions reported via Rails.error (including those rescued by rescue_from in controllers). This fills the gap where process_action.action_controller only includes exception data for unhandled exceptions — rescued exceptions show status 500 but no exception_class, backtrace, or error_fingerprint.

Registered automatically in the Railtie when Rails.error is available.

Constant Summary collapse

SEVERITY_MAP =
{
  error: "ERROR",
  warning: "WARN",
  info: "INFO"
}.freeze

Instance Method Summary collapse

Instance Method Details

#report(error, handled:, severity:, context: {}, source: nil) ⇒ Object



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
56
57
58
59
60
61
62
63
# File 'lib/opentrace/error_subscriber.rb', line 20

def report(error, handled:, severity:, context: {}, source: nil)
  return unless OpenTrace.enabled?

  # Skip if already inside an OpenTrace logging call (re-entrance guard)
  return if Fiber[:opentrace_logging]

  level = SEVERITY_MAP[severity] || "ERROR"

  meta = {}
  meta[:exception_class] = error.class.name
  meta[:exception_message] = error.message&.slice(0, 500)
  meta[:handled] = handled
  meta[:error_source] = source if source

  if error.backtrace
    cleaned = clean_backtrace(error.backtrace)
    meta[:backtrace] = cleaned.first(15)
  end

  # Capture exception cause chain
  if error.cause
    meta[:exception_causes] = OpenTrace.send(:build_cause_chain, error.cause, depth: 0)
  end

  # Include request params from context if available
  if context[:params].is_a?(Hash)
    params = context[:params].except("controller", "action")
    meta[:params] = truncate_hash(params, 2048) unless params.empty?
  end

  # Include controller/action context
  meta[:controller] = context[:controller] if context[:controller]
  meta[:action] = context[:action] if context[:action]

  # Merge any additional context from the reporter
  context.each do |k, v|
    next if %i[params controller action].include?(k)
    meta[k] = v
  end

  OpenTrace.log(level, "#{error.class}: #{error.message&.slice(0, 200)}", meta)
rescue StandardError
  # Never raise to the host app
end