Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add context to errors in JSON.mapping #5932

Merged
merged 2 commits into from
Apr 22, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 45 additions & 3 deletions spec/std/json/mapping_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,11 @@ describe "JSON mapping" do
end

it "parses strict person with unknown attributes" do
ex = expect_raises JSON::ParseException, "Unknown json attribute: foo" do
error_message = <<-'MSG'
Unknown JSON attribute: foo
parsing StrictJSONPerson
MSG
ex = expect_raises JSON::MappingError, error_message do
StrictJSONPerson.from_json <<-JSON
{
"name": "John",
Expand All @@ -234,12 +238,46 @@ describe "JSON mapping" do
end

it "raises if non-nilable attribute is nil" do
ex = expect_raises JSON::ParseException, "Missing json attribute: name" do
error_message = <<-'MSG'
Missing JSON attribute: name
parsing JSONPerson at 1:1
MSG
ex = expect_raises JSON::MappingError, error_message do
JSONPerson.from_json(%({"age": 30}))
end
ex.location.should eq({1, 1})
end

it "raises if not an object" do
error_message = <<-'MSG'
Expected begin_object but was string at 1:1
parsing StrictJSONPerson at 0:0
MSG
ex = expect_raises JSON::MappingError, error_message do
StrictJSONPerson.from_json <<-JSON
"foo"
JSON
end
ex.location.should eq({1, 1})
end

it "raises if data type does not match" do
error_message = <<-'MSG'
Expected int but was string at 3:15
parsing StrictJSONPerson#age at 3:3
MSG
ex = expect_raises JSON::MappingError, error_message do
StrictJSONPerson.from_json <<-JSON
{
"name": "John",
"age": "foo",
"foo": "bar"
}
JSON
end
ex.location.should eq({3, 15})
end

it "doesn't emit null by default when doing to_json" do
person = JSONPerson.from_json(%({"name": "John"}))
(person.to_json =~ /age/).should be_falsey
Expand Down Expand Up @@ -523,7 +561,11 @@ describe "JSON mapping" do
end

it "raises if non-nilable attribute is nil" do
ex = expect_raises JSON::ParseException, "Missing json attribute: foo" do
error_message = <<-'MSG'
Missing JSON attribute: foo
parsing JSONWithQueryAttributes at 1:1
MSG
ex = expect_raises JSON::MappingError, error_message do
JSONWithQueryAttributes.from_json(%({"is_bar": true}))
end
ex.location.should eq({1, 1})
Expand Down
4 changes: 2 additions & 2 deletions src/json.cr
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ module JSON
getter line_number : Int32
getter column_number : Int32

def initialize(message, @line_number, @column_number)
super "#{message} at #{@line_number}:#{@column_number}"
def initialize(message, @line_number, @column_number, cause = nil)
super "#{message} at #{@line_number}:#{@column_number}", cause
end

def location
Expand Down
81 changes: 60 additions & 21 deletions src/json/mapping.cr
Original file line number Diff line number Diff line change
Expand Up @@ -101,40 +101,46 @@ module JSON
{% end %}

%location = %pull.location
%pull.read_begin_object
begin
%pull.read_begin_object
rescue exc : ::JSON::ParseException
raise ::JSON::MappingError.new(self.class, *%location, cause: exc)
end
while %pull.kind != :end_object
%key_location = %pull.location
key = %pull.read_object_key
case key
{% for key, value in _properties_ %}
when {{value[:key] || value[:key_id].stringify}}
%found{key.id} = true
begin
%var{key.id} =
{% if value[:nilable] || value[:default] != nil %} %pull.read_null_or { {% end %}

%var{key.id} =
{% if value[:nilable] || value[:default] != nil %} %pull.read_null_or { {% end %}

{% if value[:root] %}
%pull.on_key!({{value[:root]}}) do
{% end %}

{% if value[:converter] %}
{{value[:converter]}}.from_json(%pull)
{% elsif value[:type].is_a?(Path) || value[:type].is_a?(Generic) %}
{{value[:type]}}.new(%pull)
{% else %}
::Union({{value[:type]}}).new(%pull)
{% end %}
{% if value[:root] %}
%pull.on_key!({{value[:root]}}) do
{% end %}

{% if value[:root] %}
end
{% end %}
{% if value[:converter] %}
{{value[:converter]}}.from_json(%pull)
{% elsif value[:type].is_a?(Path) || value[:type].is_a?(Generic) %}
{{value[:type]}}.new(%pull)
{% else %}
::Union({{value[:type]}}).new(%pull)
{% end %}

{% if value[:nilable] || value[:default] != nil %} } {% end %}
{% if value[:root] %}
end
{% end %}

{% if value[:nilable] || value[:default] != nil %} } {% end %}
rescue exc : ::JSON::ParseException
raise ::JSON::MappingError.new(self.class, {{value[:key] || value[:key_id].stringify}}, *%key_location, cause: exc)
end
{% end %}
else
{% if strict %}
raise ::JSON::ParseException.new("Unknown json attribute: #{key}", *%key_location)
raise ::JSON::MappingError.new("Unknown JSON attribute: #{key}", self.class, *%key_location)
{% else %}
%pull.skip
{% end %}
Expand All @@ -145,7 +151,7 @@ module JSON
{% for key, value in _properties_ %}
{% unless value[:nilable] || value[:default] != nil %}
if %var{key.id}.nil? && !%found{key.id} && !::Union({{value[:type]}}).nilable?
raise ::JSON::ParseException.new("Missing json attribute: {{(value[:key] || value[:key_id]).id}}", *%location)
raise ::JSON::MappingError.new("Missing JSON attribute: {{(value[:key] || value[:key_id]).id}}", self.class, *%location)
end
{% end %}

Expand Down Expand Up @@ -220,4 +226,37 @@ module JSON
macro mapping(**_properties_)
::JSON.mapping({{_properties_}})
end

class MappingError < ParseException
getter klass : String
getter attribute : String?

def self.new(klass : Class, line_number, column_number, *, cause : JSON::ParseException)
new(cause.message, klass, nil, line_number, column_number, cause: cause)
end

def self.new(klass : Class, attribute, line_number, column_number, *, cause : JSON::ParseException)
new(cause.message, klass, attribute, line_number, column_number, cause: cause)
end

def self.new(message : String?, klass : String | Class, line_number : Int32, column_number : Int32, cause = nil)
new(message, klass, nil, line_number, column_number, cause)
end

def initialize(message : String?, klass : String | Class, @attribute : String?, line_number : Int32, column_number : Int32, cause = nil)
message = String.build do |io|
io << message
io << "\n parsing "
io << klass
if attribute = @attribute
io << '#' << attribute
end
end
super(message, line_number, column_number, cause)
if cause
@line_number, @column_number = cause.location
end
@klass = klass.to_s
end
end
end