Skip to content

Commit feb72b1

Browse files
committed
Highlight where the error occurred in the JSON syntax error
1 parent 0824ccb commit feb72b1

1 file changed

Lines changed: 18 additions & 3 deletions

File tree

config/config.go

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import (
44
"encoding/json"
55
"errors"
66
"fmt"
7+
"io"
8+
"log"
79
"os"
810
"path/filepath"
911
"runtime"
@@ -143,15 +145,28 @@ func (c *Config) read() error {
143145

144146
if err := json.NewDecoder(f).Decode(&c); err != nil {
145147
var extra string
146-
if _, ok := err.(*json.SyntaxError); ok {
147-
extra = ":\nThe file contains invalid JSON syntax"
148+
if serr, ok := err.(*json.SyntaxError); ok {
149+
if _, serr := f.Seek(0, os.SEEK_SET); serr != nil {
150+
log.Fatalf("seek error: %v", serr)
151+
}
152+
extra = fmt.Sprintf(":\nThe file contains invalid JSON syntax at '%s' <~",
153+
findInvalidJSON(f, serr.Offset))
148154
}
149-
return fmt.Errorf("error parsing JSON in the config file %s%s: %s", f.Name(), extra, err)
155+
return fmt.Errorf("error parsing JSON in the config file %s%s\n%s", f.Name(), extra, err)
150156
}
151157

152158
return nil
153159
}
154160

161+
func findInvalidJSON(f io.ReaderAt, pos int64) string {
162+
buf := make([]byte, 13)
163+
if _, err := f.ReadAt(buf, pos-13); err != nil {
164+
log.Fatalf("read error: %v", err)
165+
}
166+
167+
return string(buf)
168+
}
169+
155170
// IsAuthenticated returns true if the config contains an API key.
156171
// This does not check whether or not that key is valid.
157172
func (c *Config) IsAuthenticated() bool {

0 commit comments

Comments
 (0)