Handling errors in Rails.cache.fetch
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.
I would not use fetch, in this case, and in most cases.
Fetch make you account for all flow control cases using exception handling as your only mechanism for flow control(!).
Instead, use the read and write methods for the cache, using normal flow control that results in the behavior you want. Fetch is fast and fancy, but comes with extra baggage that you aren't going to be happy with once you have to actually support the software you wrote.