mattermost/utils/jsonutils/json.go
Haardik Dharma 6356e906e0
[Partial Fix - #16623]: Fix initialism errors in codebase. (#16877)
* Update files in /app

* Update files in /plugin

* Update files in /store

* Update files in /utils

* Update files in /web

* Update store.go

* Update command_response.go

* check-mocks and check-store-layer checks

* Fix build errors

* Revert "Fix build errors"

This reverts commit 4ee38c3d0b.

* Update .golangci.yml

* make i18n-extract and make i18n-check

* Commit suggestions

* check-mocks and check-store-layers

* Update en.json

* Update product_notices.go

* Update main.go

* Fix translations

* Regenerate mocks

Co-authored-by: Mattermod <mattermod@users.noreply.github.com>
Co-authored-by: Claudio Costa <cstcld91@gmail.com>
2021-02-18 15:36:56 +01:00

56 lines
1.4 KiB
Go

// 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),
}
}