Created
August 23, 2012 10:16
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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