Browse Source

Make EOF in JSON.parse human-oriented. Fixes #503

Oleg Bespalov 2 years ago
parent
commit
b244ee5f51
2 changed files with 17 additions and 0 deletions
  1. 4 0
      builtin_json.go
  2. 13 0
      builtin_json_test.go

+ 4 - 0
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()))
 	}

+ 13 - 0
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()