Method: ActiveSupport::ErrorReporter#unexpected

Defined in:
activesupport/lib/active_support/error_reporter.rb

#unexpected(error, severity: :warning, context: {}, source: DEFAULT_SOURCE) ⇒ Object

Either report the given error when in production, or raise it when in development or test.

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

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

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

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

example:

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


145
146
147
148
149
150
151
152
153
154
# File 'activesupport/lib/active_support/error_reporter.rb', line 145

def unexpected(error, severity: :warning, context: {}, source: DEFAULT_SOURCE)
  error = RuntimeError.new(error) if error.is_a?(String)
  error.set_backtrace(caller(1)) if error.backtrace.nil?

  if @debug_mode
    raise UnexpectedError, "#{error.class.name}: #{error.message}", error.backtrace, cause: error
  else
    report(error, handled: true, severity: severity, context: context, source: source)
  end
end