public
Last active

Handling Parsing errors using Rack middleware in Rails 3.2

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#in application.rb
module YourApp
class Application < Rails::Application
config.middleware.insert_before ActionDispatch::ParamsParser, "ParsingFailureToJSON"
...
end
end
 
#The Parsing failure middleware
class ParsingFailureToJSON
def initialize app
@app = app
end
 
def call env
begin
@app.call(env)
rescue DecodeError #Obviously, this should be the error that you are interested in
RailsFailureController.action(:parsing).call(env)
end
end
end
 
#RailsFailureController is a controller that can render anything using the full rails view layer.
#It makes rendering parsing errors using reusable error templates easy. You don't have to use a controller though

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.