Class: CatchJsonParseErrors::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/catch_json_parse_errors/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



3
4
5
# File 'lib/catch_json_parse_errors/middleware.rb', line 3

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/catch_json_parse_errors/middleware.rb', line 7

def call(env)
  @app.call(env)
rescue ActionDispatch::ParamsParser::ParseError => error
  if env['HTTP_ACCEPT'] =~ /application\/json/
    error_output = "There was a problem in the JSON you submitted: #{error}"
    return [
      400, { "Content-Type" => "application/json" },
      [ { status: 400, error: error_output }.to_json ]
    ]
  else
    raise error
  end
end