MM-10232, MM-10259: Improve error handling from invalid json (#8668)

* MM-10232: improve error handling from malformed slash command responses

Switch to json.Unmarshal, which doesn't obscure JSON parse failures like
json.Decode. The latter is primarily designed for streams of JSON, not
necessarily unmarshalling just a single object.

* rework HumanizedJsonError to expose Line and Character discretely

* MM-10259: pinpoint line and character where json config error occurs

* tweak HumanizeJsonError to accept err first
Этот коммит содержится в:
Jesse Hallam
2018-04-26 11:19:25 -04:00
коммит произвёл GitHub
родитель d3f09b54e2
Коммит 6d50d836f5
12 изменённых файлов: 487 добавлений и 109 удалений

Просмотреть файл

@@ -8,6 +8,8 @@ import (
"io"
"io/ioutil"
"strings"
"github.com/mattermost/mattermost-server/utils/jsonutils"
)
const (
@@ -31,14 +33,14 @@ func (o *CommandResponse) ToJson() string {
return string(b)
}
func CommandResponseFromHTTPBody(contentType string, body io.Reader) *CommandResponse {
func CommandResponseFromHTTPBody(contentType string, body io.Reader) (*CommandResponse, error) {
if strings.TrimSpace(strings.Split(contentType, ";")[0]) == "application/json" {
return CommandResponseFromJson(body)
}
if b, err := ioutil.ReadAll(body); err == nil {
return CommandResponseFromPlainText(string(b))
return CommandResponseFromPlainText(string(b)), nil
}
return nil
return nil, nil
}
func CommandResponseFromPlainText(text string) *CommandResponse {
@@ -47,15 +49,19 @@ func CommandResponseFromPlainText(text string) *CommandResponse {
}
}
func CommandResponseFromJson(data io.Reader) *CommandResponse {
decoder := json.NewDecoder(data)
var o CommandResponse
func CommandResponseFromJson(data io.Reader) (*CommandResponse, error) {
b, err := ioutil.ReadAll(data)
if err != nil {
return nil, err
}
if err := decoder.Decode(&o); err != nil {
return nil
var o CommandResponse
err = json.Unmarshal(b, &o)
if err != nil {
return nil, jsonutils.HumanizeJsonError(err, b)
}
o.Attachments = StringifySlackFieldValue(o.Attachments)
return &o
return &o, nil
}