From a938b0dee988641c4eac71f03df35a0df3095f18 Mon Sep 17 00:00:00 2001 From: Joonas Loppi Date: Wed, 12 Jul 2023 12:13:47 +0300 Subject: [PATCH] `encoding/jsonfile`: stutter less (JSON is already mentioned in inner error) --- encoding/jsonfile/jsonfile.go | 4 +++- encoding/jsonfile/jsonfile_test.go | 12 ++++++++++++ encoding/jsonfile/testdata/example.json | 3 +++ 3 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 encoding/jsonfile/jsonfile_test.go create mode 100644 encoding/jsonfile/testdata/example.json diff --git a/encoding/jsonfile/jsonfile.go b/encoding/jsonfile/jsonfile.go index 0bb345b..8719701 100644 --- a/encoding/jsonfile/jsonfile.go +++ b/encoding/jsonfile/jsonfile.go @@ -54,7 +54,9 @@ func unmarshalInternal(source io.Reader, data interface{}, disallowUnknownFields if err := jsonDecoder.Decode(data); err != nil { // sadly, line numbers are only possible with hacks (requiring buffering): // https://github.com/hashicorp/packer/blob/master/common/json/unmarshal.go - return fmt.Errorf("JSON parsing failed: %s", err.Error()) + // + // no need mention JSON as context in error message, because `err` already mentions that. + return fmt.Errorf("decode failed: %s", err.Error()) } return nil diff --git a/encoding/jsonfile/jsonfile_test.go b/encoding/jsonfile/jsonfile_test.go new file mode 100644 index 0000000..bac57bf --- /dev/null +++ b/encoding/jsonfile/jsonfile_test.go @@ -0,0 +1,12 @@ +package jsonfile + +import ( + "testing" + + "github.com/function61/gokit/testing/assert" +) + +func TestRead(t *testing.T) { + assert.Equal(t, ReadDisallowUnknownFields("notfound.json", &struct{}{}).Error(), "open notfound.json: no such file or directory") + assert.Equal(t, ReadDisallowUnknownFields("testdata/example.json", &struct{}{}).Error(), `testdata/example.json: decode failed: json: unknown field "foo"`) +} diff --git a/encoding/jsonfile/testdata/example.json b/encoding/jsonfile/testdata/example.json new file mode 100644 index 0000000..460b533 --- /dev/null +++ b/encoding/jsonfile/testdata/example.json @@ -0,0 +1,3 @@ +{ + "foo": "bar" +}