Skip to content

Instantly share code, notes, and snippets.

@mclosson
Created August 23, 2012 10:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mclosson/3435169 to your computer and use it in GitHub Desktop.
Save mclosson/3435169 to your computer and use it in GitHub Desktop.
Return a JSON response to a malformed JSON request which throws an MultiJson::DecodeError exception in ActionDispatch before a controller is instanciated. Without this the ShowExceptions rack middleware will render an HTML error page to your JSON respons
# config/application.rb
# You must either set the following in this file or set consider_all_requests_local to false in config/environments/development.rb
config.middleware.delete ActionDispatch::DebugExceptions
# config/environments/development.rb
# You must either set the following in this file or disable ActionDispatch::DebugExceptions in config/application.rb
config.consider_all_requests_local = false
# config/initializers/show_exceptions.rb
# Tell ShowExceptions rack middleware to render a JSON response to a MultiJson::DecodeError exception instead of an HTML page.
class ActionDispatch::ShowExceptions
def call(env)
status, headers, body = @app.call(env)
if headers['X-Cascade'] == 'pass'
raise ActionController::RoutingError, "No route matches #{env['PATH_INFO'].inspect}"
end
[status, headers, body]
rescue Exception => exception
raise exception if env['action_dispatch.show_exceptions'] == false
if exception.class == MultiJson::DecodeError
[422, {'Content-Type' => 'application/json'}, ['{"error":"Invalid JSON"}']]
else
render_exception(env, exception)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment