Search code examples
ruby-on-railsrubygrape-api

What should return the Grape rescue_from :all block?


The Grape documentation says that:
The rescue_from block must return a Rack::Response object, call error! or re-raise an exception.

but if we use the rescue_from method only to log things and we want to keep the original HTTP answer what should we return ?

If I rethrow the catched exception, it does not keep the original behavior. For example, some of my tests generate 400 responses but with:

rescue_from :all do |e|
  Rails.logger.error(e)
  raise e
end

They catch 500 responses.

The better solution I found to reproduce the original behavior is this code:

rescue_from :all do |e|
  Rails.logger.error(e)
  if e.respond_to?(:status)
    error!(e.to_json, e.status, e.headers, e.backtrace)
  else
    error! "Internal Server Error"
  end
end

I should check if the catched exception responds to status because it could be a RuntimeError for example, and RuntimeError does not answer to status.

Am I doing this right ? Or there is a better solution to do that ?


Solution

  • This is answered in https://github.com/ruby-grape/grape/pull/939, pointed from https://github.com/ruby-grape/grape/issues/1300.