I'm using Rails.cache to cache a response from an API:
Rails.cache.fetch("key") do
api.get "/api/data"
api.body
end
The API isn't very reliable, and occasionally I get a 500 error. I'd like to avoid caching the 500 response.
Rails.cache.fetch("key") do
api.get "/api/data"
if api.body.meta.status == 500
# Bail out, Goose!
end
api.body
end
I would rather not raise an exception. What is the best way to "bail out" of the block without caching?
I just ran into this myself and it looks like a break
will solve our problems. I just tested this locally against the memory_store and the dalli_store and it avoids caching the block. So for your example, try something like this:
Rails.cache.fetch("key") do
api.get "/api/data"
break if api.body.meta.status == 500
api.body
end
As a side note, if using the dalli_store it will not cache nil values so you can just return nil from the block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With