diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c8327a..b4550ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [Unreleased] +### Added +- `INVALID_BODY_FORMAT` JSON:API error + +### Changed +- Rescue and translate `MultiJson::ParseError` while parsing body + ## [2.1.0] - 2020-04-01 ### Added - Headers validation diff --git a/README.md b/README.md index ed90393..f996019 100644 --- a/README.md +++ b/README.md @@ -295,6 +295,7 @@ with one issue per line. | `:code` | `:status` | What is it? | |:--------------------------|:----------|:------------| | INVALID_RESOURCE_SCHEMA | 422 | Resource did not pass configured validation | +| INVALID_BODY_FORMAT | 400 | Request body is invalid JSON | | INVALID_QUERY_PARAMETER | 400 | Query parameter violates syntax or did not pass configured validation | | MISSING_QUERY_PARAMETER | 400 | Query parameter required in configuration is missing | | INVALID_JSON_API | 400 | Request body violates JSON:API syntax | diff --git a/lib/request_handler/body_parser.rb b/lib/request_handler/body_parser.rb index 827fa7e..c8f9512 100644 --- a/lib/request_handler/body_parser.rb +++ b/lib/request_handler/body_parser.rb @@ -30,6 +30,10 @@ def request_body b.rewind b = b.read b.empty? ? {} : MultiJson.load(b) + rescue MultiJson::ParseError => e + raise BodyFormatError, [{ status: '400', + code: 'INVALID_BODY_FORMAT', + detail: e.message }] end attr_reader :request, :schema, :schema_options, :type diff --git a/lib/request_handler/error.rb b/lib/request_handler/error.rb index d1720ee..85b02a6 100644 --- a/lib/request_handler/error.rb +++ b/lib/request_handler/error.rb @@ -42,6 +42,8 @@ class OptionNotAllowedError < JsonApiError class NoConfigAvailableError < InternalBaseError end + class BodyFormatError < ExternalArgumentError + end class BodyParamsError < ExternalArgumentError end class FieldsetsParamsError < ExternalArgumentError diff --git a/spec/request_handler/body_parser_spec.rb b/spec/request_handler/body_parser_spec.rb index b9f8172..a057d85 100644 --- a/spec/request_handler/body_parser_spec.rb +++ b/spec/request_handler/body_parser_spec.rb @@ -103,6 +103,20 @@ .to raise_error(RequestHandler::MissingArgumentError) end + it 'fails if the request body is not json' do + schema = Dry::Schema.JSON {} + expect do + described_class.new( + schema: schema, + type: type, + request: instance_double('Rack::Request', + params: {}, + body: StringIO.new('foo')) + ).run + end + .to raise_error(RequestHandler::BodyFormatError) + end + it "doesn't fail if the request body does not contain a data hash" do schema = Dry::Schema.JSON {} expect do