Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling errors in Rails.cache.fetch

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?

like image 959
thesmart Avatar asked Nov 14 '13 04:11

thesmart


1 Answers

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.

like image 182
Eric Hutzelman Avatar answered Oct 14 '22 22:10

Eric Hutzelman