From 4e50fd864921c556988c919269448efdb90fa961 Mon Sep 17 00:00:00 2001 From: Wim Date: Mon, 10 Aug 2020 00:29:54 +0200 Subject: Use mattermost v5 module (#1192) --- .../mattermost-server/v5/utils/jsonutils/json.go | 56 ++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 vendor/github.com/mattermost/mattermost-server/v5/utils/jsonutils/json.go (limited to 'vendor/github.com/mattermost/mattermost-server/v5/utils/jsonutils') diff --git a/vendor/github.com/mattermost/mattermost-server/v5/utils/jsonutils/json.go b/vendor/github.com/mattermost/mattermost-server/v5/utils/jsonutils/json.go new file mode 100644 index 00000000..4651ec87 --- /dev/null +++ b/vendor/github.com/mattermost/mattermost-server/v5/utils/jsonutils/json.go @@ -0,0 +1,56 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package jsonutils + +import ( + "bytes" + "encoding/json" + + "github.com/pkg/errors" +) + +type HumanizedJsonError struct { + Err error + Line int + Character int +} + +func (e *HumanizedJsonError) Error() string { + return e.Err.Error() +} + +// HumanizeJsonError extracts error offsets and annotates the error with useful context +func HumanizeJsonError(err error, data []byte) error { + if syntaxError, ok := err.(*json.SyntaxError); ok { + return NewHumanizedJsonError(syntaxError, data, syntaxError.Offset) + } else if unmarshalError, ok := err.(*json.UnmarshalTypeError); ok { + return NewHumanizedJsonError(unmarshalError, data, unmarshalError.Offset) + } else { + return err + } +} + +func NewHumanizedJsonError(err error, data []byte, offset int64) *HumanizedJsonError { + if err == nil { + return nil + } + + if offset < 0 || offset > int64(len(data)) { + return &HumanizedJsonError{ + Err: errors.Wrapf(err, "invalid offset %d", offset), + } + } + + lineSep := []byte{'\n'} + + line := bytes.Count(data[:offset], lineSep) + 1 + lastLineOffset := bytes.LastIndex(data[:offset], lineSep) + character := int(offset) - (lastLineOffset + 1) + 1 + + return &HumanizedJsonError{ + Line: line, + Character: character, + Err: errors.Wrapf(err, "parsing error at line %d, character %d", line, character), + } +} -- cgit v1.2.3