FIX: Ensure RequestTracker handles bubbled exceptions correctly (#26940)

This can happen for various reasons including rate limiting and middleware bugs. This should resolve the warning we're seeing in the logs

```
RequestTracker.get_data failed : NoMethodError : undefined method `[]' for nil:NilClass
```
This commit is contained in:
David Taylor 2024-05-08 16:08:39 +01:00 committed by GitHub
parent c8faf3e427
commit ece0150cb7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 21 additions and 0 deletions

View File

@ -120,7 +120,10 @@ class Middleware::RequestTracker
def self.get_data(env, result, timing, request = nil)
status, headers = result
# result may be nil if the downstream app raised an exception
status = status.to_i
headers ||= {}
request ||= Rack::Request.new(env)
helper = Middleware::AnonymousCache::Helper.new(env, request)

View File

@ -816,4 +816,22 @@ RSpec.describe Middleware::RequestTracker do
expect(@data[:background_type]).to eq("message-bus-dontchunk")
end
end
describe "error handling" do
before do
@original_logger = Rails.logger
Rails.logger = @fake_logger = FakeLogger.new
end
after { Rails.logger = @original_logger }
it "logs requests even if they cause exceptions" do
app = lambda { |env| raise RateLimiter::LimitExceeded, 1 }
tracker = Middleware::RequestTracker.new(app)
expect { tracker.call(env) }.to raise_error(RateLimiter::LimitExceeded)
CachedCounting.flush
expect(ApplicationRequest.stats).to include("http_total_total" => 1)
expect(@fake_logger.warnings).to be_empty
end
end
end