Created
March 30, 2015 10:56
-
-
Save oojikoo-gist/8b06f41c28ba4a232243 to your computer and use it in GitHub Desktop.
rails: Catching Invalid JSON Parse Errors
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
class CatchJsonParseErrors | |
def initialize app | |
@app = app | |
end | |
def call env | |
begin | |
@app.call(env) | |
rescue ActionDispatch::ParamsParser::ParseError => exception | |
content_type_is_json?(env) ? build_response(exception) : raise(exception) | |
end | |
end | |
private | |
def content_type_is_json? env | |
env['CONTENT_TYPE'] =~ /application\/json/ | |
end | |
def error_message exception | |
"Payload data is not valid JSON. Error message: #{exception}" | |
end | |
def build_response exception | |
[ 400, { "Content-Type" => "application/json" }, [ { error: error_message(exception) }.to_json ] ] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment