Search code examples
ruby-on-railsrubyerror-handlingrubygemsbrakeman

Brakeman does not like rescue


I have this method inside a model with this code inside. It calls a gem and returns either the object I want or a 404 resource not found. if I do a method on a 404 then I need to rescue it as shown below. If I just use rescue the linter fails. If I do this brakeman fails.

find_object
  return_object = Rails.cache.fetch(cache_key + '/variableInsideObject') do
    GemClient.find(id).variableInsideObject
    rescue HttpServices::ResourceNotFoundError
    raise ApplicationController::ExternalServiceError,
        "variable inside object not found for id: #{id}"
  end
end

How can I rescue this error without failing the linter and brakeman.


Solution

  • Imo this is a more Ruby-esque implementation of this code:

    def find_object
      return_object = begin
        Rails.cache.fetch(cache_key + '/variableInsideObject') do
          GemClient.find(id).variableInsideObject
        end
      rescue HttpServices::ResourceNotFoundError => e
        Rails.logger.error(e)
        raise ApplicationController::ExternalServiceError,
          "variable inside object not found for id: #{id}"
      end
    end
    

    Of course, it's hard to say without knowing what the linter or brakeman are complaining about exactly.... but this should be better. You don't of course need to use begin end blocks, but sometimes linters/community finds it is neater...