From b244ee5f51185b206b42296afb97a724310cf60c Mon Sep 17 00:00:00 2001 From: Oleg Bespalov Date: Fri, 26 May 2023 08:47:25 +0200 Subject: [PATCH] Make EOF in JSON.parse human-oriented. Fixes #503 --- builtin_json.go | 4 ++++ builtin_json_test.go | 13 +++++++++++++ 2 files changed, 17 insertions(+) diff --git a/builtin_json.go b/builtin_json.go index 8fa238af..b3425265 100644 --- a/builtin_json.go +++ b/builtin_json.go @@ -3,6 +3,7 @@ package goja import ( "bytes" "encoding/json" + "errors" "fmt" "io" "math" @@ -20,6 +21,9 @@ func (r *Runtime) builtinJSON_parse(call FunctionCall) Value { d := json.NewDecoder(strings.NewReader(call.Argument(0).toString().String())) value, err := r.builtinJSON_decodeValue(d) + if errors.Is(err, io.EOF) { + panic(r.newError(r.global.SyntaxError, "Unexpected end of JSON input (%v)", err.Error())) + } if err != nil { panic(r.newError(r.global.SyntaxError, err.Error())) } diff --git a/builtin_json_test.go b/builtin_json_test.go index 164c3fdf..4c41d296 100644 --- a/builtin_json_test.go +++ b/builtin_json_test.go @@ -65,6 +65,19 @@ func TestQuoteMalformedSurrogatePair(t *testing.T) { testScript(`JSON.stringify("\uD800")`, asciiString(`"\ud800"`), t) } +func TestEOFWrapping(t *testing.T) { + vm := New() + + _, err := vm.RunString("JSON.parse('{')") + if err == nil { + t.Fatal("Expected error") + } + + if !strings.Contains(err.Error(), "Unexpected end of JSON input") { + t.Fatalf("Error doesn't contain human-friendly wrapper: %v", err) + } +} + func BenchmarkJSONStringify(b *testing.B) { b.StopTimer() vm := New()