Sha256: 73fff05b93aef9e7e780faec7ecd7551828e02f249729770192b738c74a76166

Contents?: true

Size: 1.01 KB

Versions: 2

Compression:

Stored size: 1.01 KB

Contents

module FunWithJsonApi
  module Middleware
    class CatchJsonApiParseErrors
      JSON_API_REGEX = %r{application\/vnd\.api\+json}

      def initialize(app)
        @app = app
      end

      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

      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

      def respond_with_json_api_error?(env)
        FunWithJsonApi.configuration.force_render_parse_errors_as_json_api? ||
          env['HTTP_ACCEPT'] =~ JSON_API_REGEX
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
fun_with_json_api-0.0.14 lib/fun_with_json_api/middleware/catch_json_api_parse_errors.rb
fun_with_json_api-0.0.13 lib/fun_with_json_api/middleware/catch_json_api_parse_errors.rb