class ActiveSupport::ErrorReporter


maybe_tags = Rails.error.handle(Redis::BaseError) { redis.get(“tags”) }
Both methods can be restricted to handle only a specific error class:
end
do_something!
Rails.error.record do
Alternatively, if you want to report the error but not swallow it, you can use #record:
If an error is raised, it will be reported and swallowed.
end
do_something!
Rails.error.handle do
To rescue and report any unhandled error, you can use the #handle method:
ActiveSupport::ErrorReporter is a common interface for error reporting services.
= Active Support Error Reporter

def disable(subscriber)

to handle any errors higher in the stack.
This can be helpful for error reporting service integrations, when they wish

duration of the block. You may pass in the subscriber itself, or its class.
Prevent a subscriber from being notified of errors for the
def disable(subscriber)
  disabled_subscribers = (ActiveSupport::IsolatedExecutionState[self] ||= [])
  disabled_subscribers << subscriber
  begin
    yield
  ensure
    disabled_subscribers.delete(subscriber)
  end
end

def ensure_backtrace(error)

def ensure_backtrace(error)
  return if error.frozen? # re-raising won't add a backtrace
  return unless error.backtrace.nil?
  begin
    # We could use Exception#set_backtrace, but until Ruby 3.4
    # it only support setting `Exception#backtrace` and not
    # `Exception#backtrace_locations`. So raising the exception
    # is a good way to build a real backtrace.
    raise error
  rescue error.class => error
  end
  count = 0
  while error.backtrace_locations.first&.path == __FILE__
    count += 1
    error.backtrace_locations.shift
  end
  error.backtrace.shift(count)
end

def handle(*error_classes, severity: :warning, context: {}, fallback: nil, source: DEFAULT_SOURCE)

errors. Defaults to "application".
source of the error. Subscribers can use this value to ignore certain
* +:source+ - This value is passed along to subscribers to indicate the

end
User.find_by(params)
user = Rails.error.handle(fallback: -> { User.anonymous }) do

unhandled error is raised. For example:
* +:fallback+ - A callable that provides +handle+'s return value when an

end
# ...
Rails.error.handle(context: { section: "admin" }) do

example:
* +:context+ - Extra information that is passed along to subscribers. For

Defaults to +:warning+.
important the error report is. Can be +:error+, +:warning+, or +:info+.
* +:severity+ - This value is passed along to subscribers to indicate how

==== Options

maybe_tags = Rails.error.handle(Redis::BaseError) { redis.get("tags") }

Can be restricted to handle only specific error classes:

end
1 + '1'
Rails.error.handle do
# Will report a TypeError to all subscribers and return nil.

specified.
returns the result of +fallback.call+, or +nil+ if +fallback+ is not
If no error is raised, returns the return value of the block. Otherwise,
Evaluates the given block, reporting and swallowing any unhandled error.
def handle(*error_classes, severity: :warning, context: {}, fallback: nil, source: DEFAULT_SOURCE)
  error_classes = DEFAULT_RESCUE if error_classes.empty?
  yield
rescue *error_classes => error
  report(error, handled: true, severity: severity, context: context, source: source)
  fallback.call if fallback
end

def initialize(*subscribers, logger: nil)

def initialize(*subscribers, logger: nil)
  @subscribers = subscribers.flatten
  @logger = logger
  @debug_mode = false
end

def record(*error_classes, severity: :error, context: {}, source: DEFAULT_SOURCE)

errors. Defaults to "application".
source of the error. Subscribers can use this value to ignore certain
* +:source+ - This value is passed along to subscribers to indicate the

end
# ...
Rails.error.record(context: { section: "admin" }) do

example:
* +:context+ - Extra information that is passed along to subscribers. For

Defaults to +:error+.
important the error report is. Can be +:error+, +:warning+, or +:info+.
* +:severity+ - This value is passed along to subscribers to indicate how

==== Options

tags = Rails.error.record(Redis::BaseError) { redis.get("tags") }

Can be restricted to handle only specific error classes:

end
1 + '1'
Rails.error.record do
# Will report a TypeError to all subscribers and re-raise it.

If no error is raised, returns the return value of the block.
Evaluates the given block, reporting and re-raising any unhandled error.
def record(*error_classes, severity: :error, context: {}, source: DEFAULT_SOURCE)
  error_classes = DEFAULT_RESCUE if error_classes.empty?
  yield
rescue *error_classes => error
  report(error, handled: false, severity: severity, context: context, source: source)
  raise
end

def report(error, handled: true, severity: handled ? :warning : :error, context: {}, source: DEFAULT_SOURCE)

string argument.
Otherwise you can use #unexpected to report an error which does accept a

Rails.error.report(Exception.new("Something went wrong"))

The +error+ argument must be an instance of Exception.

Rails.error.report(error)

block-based #handle and #record methods are not suitable.
Report an error directly to subscribers. You can use this method when the
def report(error, handled: true, severity: handled ? :warning : :error, context: {}, source: DEFAULT_SOURCE)
  return if error.instance_variable_defined?(:@__rails_error_reported)
  ensure_backtrace(error)
  unless SEVERITIES.include?(severity)
    raise ArgumentError, "severity must be one of #{SEVERITIES.map(&:inspect).join(", ")}, got: #{severity.inspect}"
  end
  full_context = ActiveSupport::ExecutionContext.to_h.merge(context)
  disabled_subscribers = ActiveSupport::IsolatedExecutionState[self]
  @subscribers.each do |subscriber|
    unless disabled_subscribers&.any? { |s| s === subscriber }
      subscriber.report(error, handled: handled, severity: severity, context: full_context, source: source)
    end
  rescue => subscriber_error
    if logger
      logger.fatal(
        "Error subscriber raised an error: #{subscriber_error.message} (#{subscriber_error.class})\n" +
        subscriber_error.backtrace.join("\n")
      )
    else
      raise
    end
  end
  while error
    unless error.frozen?
      error.instance_variable_set(:@__rails_error_reported, true)
    end
    error = error.cause
  end
  nil
end

def set_context(...)


Rails.error.set_context(section: "checkout", user_id: @user.id)

context set here.
context passed to #handle, #record, or #report will be merged with the
Update the execution context that is accessible to error subscribers. Any
def set_context(...)
  ActiveSupport::ExecutionContext.set(...)
end

def subscribe(subscriber)

The +report+ method should never raise an error.

report(Exception, handled: Boolean, severity: (:error OR :warning OR :info), context: Hash, source: String)

Register a new error subscriber. The subscriber must respond to
def subscribe(subscriber)
  unless subscriber.respond_to?(:report)
    raise ArgumentError, "Error subscribers must respond to #report"
  end
  @subscribers << subscriber
end

def unexpected(error, severity: :warning, context: {}, source: DEFAULT_SOURCE)


end
# ...
end
return false
Rails.error.unexpected("[BUG] Attempting to edit a published article, that shouldn't be possible")
if published?
def edit

example:

The error can be either an exception instance or a String.

cases that can and should be gracefully handled in production, but that aren't supposed to happen.
This method is intended for reporting violated assertions about preconditions, or similar

it's not being rescued higher in the stack and will be surfaced to the developer.
When called in development, the original error is wrapped in a different error class to ensure

nil and execution will continue.
When called in production, after the error is reported, this method will return

Either report the given error when in production, or raise it when in development or test.
def unexpected(error, severity: :warning, context: {}, source: DEFAULT_SOURCE)
  error = RuntimeError.new(error) if error.is_a?(String)
  if @debug_mode
    ensure_backtrace(error)
    raise UnexpectedError, "#{error.class.name}: #{error.message}", error.backtrace, cause: error
  else
    report(error, handled: true, severity: severity, context: context, source: source)
  end
end

def unsubscribe(subscriber)

Rails.error.unsubscribe(MyErrorSubscriber)
# or
Rails.error.unsubscribe(subscriber)

Rails.error.subscribe(subscriber)
subscriber = MyErrorSubscriber.new

Unregister an error subscriber. Accepts either a subscriber or a class.
def unsubscribe(subscriber)
  @subscribers.delete_if { |s| subscriber === s }
end