diff --git a/errors.go b/errors.go index 29c7bcd..0cf5ef0 100644 --- a/errors.go +++ b/errors.go @@ -49,6 +49,11 @@ func (e *JSONError) Error() string { } func NewJSONError(str []byte, pos int, msg string) *JSONError { + if pos < 0 { + pos = 0 + } else if pos > len(str)-1 { + pos = len(str) - 1 + } sublen := 10 start := pos - sublen end := pos + sublen @@ -61,6 +66,6 @@ func NewJSONError(str []byte, pos int, msg string) *JSONError { substr := make([]byte, end-start+1) copy(substr, str[start:pos]) substr[pos-start] = '^' - copy(substr[pos-start+1:], str[pos+1:end]) + copy(substr[pos-start+1:], str[pos:end]) return &JSONError{pos: pos, substr: string(substr), msg: msg} } diff --git a/errors_test.go b/errors_test.go new file mode 100644 index 0000000..8ee36b2 --- /dev/null +++ b/errors_test.go @@ -0,0 +1,57 @@ +// Copyright 2019 Yunion +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package jsonutils // import "yunion.io/x/jsonutils" + +import "testing" + +func TestNewJSONError(t *testing.T) { + cases := []struct { + str []byte + pos int + }{ + { + str: []byte(`{"a":1,"b":2}`), + pos: 0, + }, + { + str: []byte(`{"a":1,"b":2}`), + pos: 1, + }, + { + str: []byte(`{"a":1,"b":2}`), + pos: 10, + }, + { + str: []byte(`{"a":1,"b":2}`), + pos: 11, + }, + { + str: []byte(`{"a":1,"b":2}`), + pos: 12, + }, + { + str: []byte(`{"a":1,"b":2}`), + pos: 5, + }, + { + str: []byte(`{"a":1,"b":2}`), + pos: 30, + }, + } + for _, c := range cases { + err := NewJSONError(c.str, c.pos, "expected a number") + t.Logf("error: %v", err) + } +}