George Shaw
George Shaw

Reputation: 1781

Ruby Grape rescue_from :all not rescuing all errors

My Grape app has several error handlers, including lastly:

rescue_from :all, backtrace: true do |e|
  message = { errors: { all: e.message } }
  rack_response(format_message(message, e.backtrace), 500 )
end

But this is not rescuing at least errors that Grape processes with

throw :error

internally. How do I rescue those errors? The particular errors noted are "The requested format 'txt' is not supported" and "Not Found: some_path". These errors occur when the format extension is missing or only a '.' is supplied, respectively.

Upvotes: 2

Views: 1636

Answers (1)

Neil Slater
Neil Slater

Reputation: 27207

You don't rescue the thrown conditions. They will go straight to the error handler, because rescue is for raised errors, not thrown conditions. throw does not create exactly the same objects as raise, and cannot be processed in the same way.

You could however, format the error message using an error_formatter:

module CustomErrorFormatter
  def self.call message, backtrace, options, env
     { errors: { all: message.to_s } }.to_json
  end
end

And in the main app:

error_formatter :json, CustomErrorFormatter

Upvotes: 1

Related Questions