2

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.

George Shaw
  • 1,771
  • 1
  • 18
  • 32

1 Answers1

1

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
Neil Slater
  • 26,512
  • 6
  • 76
  • 94
  • I thought that Grape might catch the thrown errors and Raise a Grape::Exception to unify the interface. – George Shaw Feb 20 '14 at 00:33
  • The Grape formatters assume a format extension and the two errors mentioned are because the format extension is missing (question edited). Using a default format handles the first case of no format extension, but the second of just a '.' still fails and sends text since there is no format by which to select a custom formatter. – George Shaw Feb 20 '14 at 00:38
  • @Geroge Shaw: I may be behind the times regarding raising Grape::Exception, or there may be a good reason in terms of internals to now re-direct in this way, I don't know. Are you using e.g. `default_error_formatter :json`? – Neil Slater Feb 20 '14 at 10:57
  • Tried that and it did not solve the problem. Looking closer, Grape returns a 404, and sees, I think, that it can't find a matching route. A comment in the Grape source on 'cascade?' I think applies here. I need to look at if our app can not cascade and how to do that. – George Shaw Feb 20 '14 at 19:20
  • 404 . . . Grape may not be processing those. They may coming direct from Rack. If so, you may be able to add a catch-all route at the end of the listing, so that Grape is handling them. – Neil Slater Feb 21 '14 at 23:55