Class: RailsErrorDashboard::Commands::LogError

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_error_dashboard/commands/log_error.rb

Overview

Command: Log an error to the database This is a write operation that creates an ErrorLog record

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(exception, context = {}) ⇒ LogError

Returns a new instance of LogError.



12
13
14
15
# File 'lib/rails_error_dashboard/commands/log_error.rb', line 12

def initialize(exception, context = {})
  @exception = exception
  @context = context
end

Class Method Details

.call(exception, context = {}) ⇒ Object



8
9
10
# File 'lib/rails_error_dashboard/commands/log_error.rb', line 8

def self.call(exception, context = {})
  new(exception, context).call
end

Instance Method Details

#callObject



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
56
57
58
59
60
61
# File 'lib/rails_error_dashboard/commands/log_error.rb', line 17

def call
  error_context = ValueObjects::ErrorContext.new(@context, @context[:source])

  # Build error attributes
  attributes = {
    error_type: @exception.class.name,
    message: @exception.message,
    backtrace: @exception.backtrace&.join("\n"),
    user_id: error_context.user_id,
    request_url: error_context.request_url,
    request_params: error_context.request_params,
    user_agent: error_context.user_agent,
    ip_address: error_context.ip_address,
    environment: Rails.env,
    platform: error_context.platform,
    controller_name: error_context.controller_name,
    action_name: error_context.action_name,
    occurred_at: Time.current
  }

  # Generate error hash for deduplication (including controller/action context)
  error_hash = generate_error_hash(@exception, error_context.controller_name, error_context.action_name)

  # Find existing error or create new one
  # This ensures accurate occurrence tracking
  error_log = ErrorLog.find_or_increment_by_hash(error_hash, attributes.merge(error_hash: error_hash))

  # Send notifications only for new errors (not increments)
  # Check if this is first occurrence or error was just created
  if error_log.occurrence_count == 1
    send_notifications(error_log)
    # Dispatch plugin event for new error
    PluginRegistry.dispatch(:on_error_logged, error_log)
  else
    # Dispatch plugin event for error recurrence
    PluginRegistry.dispatch(:on_error_recurred, error_log)
  end

  error_log
rescue => e
  # Don't let error logging cause more errors
  Rails.logger.error("Failed to log error: #{e.message}")
  Rails.logger.error("Backtrace: #{e.backtrace&.first(5)&.join("\n")}")
  nil
end