Context:
I love Rails.error.unexpected. I treat it like an assert, sprinkling it throughout the codebase to catch any strange behavior in dev or prod. Being able to attach custom context is incredibly useful for debugging production issues.
In production, it reports to our error subscribers, triggers alerts in our monitoring systems (Sentry, Prometheus, etc.), and logs everything properly. It’s great.
The problem is that in development, it’s not modular at all: when that unexpected case happens, you just get an exception and a stack trace. All the benefits of the context hash and custom dev error subscribers are lost.
A simple fix would be to have it call report before raising the error.
Pros:
- Would make development behavior consistent with production by reporting the error before raising, allowing us to see the behavior of our errors subscribers that manipulates
context,severity… - Would have no meaningful impact on production behavior since
reportis already called there.
References:
Code suggestion:
def unexpected(error, severity: :warning, context: {}, source: DEFAULT_SOURCE)
error = RuntimeError.new(error) if error.is_a?(String)
report(error, handled: true, severity: severity, context: context, source: source)
if @debug_mode
ensure_backtrace(error)
raise UnexpectedError, "#{error.class.name}: #{error.message}", error.backtrace, cause: error
end
end