class Commons::Middleware::CatchJsonParseErrors

Public Class Methods

new(app) click to toggle source
# File lib/commons/middleware/catch_json_parse_errors.rb, line 4
def initialize(app)
  @app = app
end

Public Instance Methods

call(env) click to toggle source
# File lib/commons/middleware/catch_json_parse_errors.rb, line 8
def call(env)
  @app.call(env)
rescue ActionDispatch::Http::Parameters::ParseError => e
  if env['HTTP_ACCEPT'] =~ %r{application/json} ||
     env['CONTENT_TYPE'] =~ %r{application/json}
    str = Commons::Errors::ErrorSerializer.new(Commons::Errors::BadRequest.new(e)).to_json
    str.tr!("'", '\'')
    return [
      '400',
      { 'Content-Type' => 'application/json' },
      [
        '{ "error":'\
        "#{str}"\
        '}'\
      ]
    ]
  else
    raise e
  end
end