Skip to content

Commit

Permalink
Fix error message when parsing unknown JSON enum value
Browse files Browse the repository at this point in the history
`#string_value` can be the value of the next token, which results in a
confusing error message.
  • Loading branch information
willhbr committed Aug 5, 2023
1 parent c592ded commit 4d117ba
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
3 changes: 3 additions & 0 deletions spec/std/json/serialization_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,9 @@ describe "JSON serialization" do
expect_raises(JSON::ParseException, %(Unknown enum JSONSpecEnum value: "three")) do
JSONSpecEnum.from_json(%("three"))
end
expect_raises(JSON::ParseException, %(Unknown enum JSONSpecEnum value: "three")) do
NamedTuple(foo: JSONSpecEnum).from_json(%({"foo": "three", "other": 1}))
end
expect_raises(JSON::ParseException, %(Expected String but was Int)) do
JSONSpecEnum.from_json(%(1))
end
Expand Down
6 changes: 4 additions & 2 deletions src/json/from_json.cr
Original file line number Diff line number Diff line change
Expand Up @@ -318,11 +318,13 @@ def Enum.new(pull : JSON::PullParser)
{% if @type.annotation(Flags) %}
value = {{ @type }}::None
pull.read_array do
value |= parse?(pull.read_string) || pull.raise "Unknown enum #{self} value: #{pull.string_value.inspect}"
string = pull.read_string
value |= parse?(string) || pull.raise "Unknown enum #{self} value: #{string.inspect}"
end
value
{% else %}
parse?(pull.read_string) || pull.raise "Unknown enum #{self} value: #{pull.string_value.inspect}"
string = pull.read_string
parse?(string) || pull.raise "Unknown enum #{self} value: #{string.inspect}"
{% end %}
end

Expand Down

0 comments on commit 4d117ba

Please sign in to comment.