Class: BadJsonRequestHandler::Middleware

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

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware



12
13
14
# File 'lib/bad_json_request_handler.rb', line 12

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/bad_json_request_handler.rb', line 16

def call(env)
  begin
    @app.call(env)
  rescue ActionDispatch::Http::Parameters::ParseError => error
    error_output = "Invalid request payload: #{error}"

    if env['CONTENT_TYPE'] =~ /application\/json/
      return [
        400,
        { "Content-Type" => "application/json" },
        [ { errors: { message: error_output } }.to_json ]
      ]
    else
      raise error, error_output
    end
  end
end