class FunWithJsonApi::Middleware::CatchJsonApiParseErrors

Constants

JSON_API_REGEX

Public Class Methods

new(app) click to toggle source
# File lib/fun_with_json_api/middleware/catch_json_api_parse_errors.rb, line 6
def initialize(app)
  @app = app
end

Public Instance Methods

call(env) click to toggle source
# File lib/fun_with_json_api/middleware/catch_json_api_parse_errors.rb, line 10
def call(env)
  @app.call(env)
rescue ActionDispatch::Http::Parameters::ParseError => error
  if env['CONTENT_TYPE'] =~ JSON_API_REGEX && respond_with_json_api_error?(env)
    build_json_api_parse_error_response
  else
    raise error
  end
end

Private Instance Methods

build_json_api_parse_error_response() click to toggle source
# File lib/fun_with_json_api/middleware/catch_json_api_parse_errors.rb, line 22
def build_json_api_parse_error_response
  title = I18n.t('fun_with_json_api.exceptions.invalid_request_body')
  [
    400, { 'Content-Type' => FunWithJsonApi::MEDIA_TYPE },
    [
      { errors: [{ code: 'invalid_request_body', title: title, status: '400' }] }.to_json
    ]
  ]
end
respond_with_json_api_error?(env) click to toggle source
# File lib/fun_with_json_api/middleware/catch_json_api_parse_errors.rb, line 32
def respond_with_json_api_error?(env)
  FunWithJsonApi.configuration.force_render_parse_errors_as_json_api? ||
    env['HTTP_ACCEPT'] =~ JSON_API_REGEX
end