Merge PR #2444: Standardize REST error responses

This commit is contained in:
Federico Kunze
2018-10-19 18:55:20 +02:00
committed by Christopher Goes
parent 505c356f20
commit ad355d6c69
20 changed files with 160 additions and 168 deletions
+29 -1
View File
@@ -2,6 +2,7 @@ package types
import (
"fmt"
"strings"
"github.com/cosmos/cosmos-sdk/codec"
cmn "github.com/tendermint/tendermint/libs/common"
@@ -286,7 +287,34 @@ func (err *sdkError) QueryResult() abci.ResponseQuery {
}
}
// nolint
//----------------------------------------
// REST error utilities
// appends a message to the head of the given error
func AppendMsgToErr(msg string, err string) string {
msgIdx := strings.Index(err, "message\":\"")
if msgIdx != -1 {
errMsg := err[msgIdx+len("message\":\"") : len(err)-2]
errMsg = fmt.Sprintf("%s; %s", msg, errMsg)
return fmt.Sprintf("%s%s%s",
err[:msgIdx+len("message\":\"")],
errMsg,
err[len(err)-2:],
)
}
return fmt.Sprintf("%s; %s", msg, err)
}
// returns the index of the message in the ABCI Log
func mustGetMsgIndex(abciLog string) int {
msgIdx := strings.Index(abciLog, "message\":\"")
if msgIdx == -1 {
panic(fmt.Sprintf("invalid error format: %s", abciLog))
}
return msgIdx + len("message\":\"")
}
// parses the error into an object-like struct for exporting
type humanReadableError struct {
Codespace CodespaceType `json:"codespace"`
Code CodeType `json:"code"`
+26
View File
@@ -1,6 +1,7 @@
package types
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
@@ -65,3 +66,28 @@ func TestErrFn(t *testing.T) {
require.Equal(t, ABCICodeOK, ToABCICode(CodespaceRoot, CodeOK))
}
func TestAppendMsgToErr(t *testing.T) {
for i, errFn := range errFns {
err := errFn("")
errMsg := err.Stacktrace().Error()
abciLog := err.ABCILog()
// plain msg error
msg := AppendMsgToErr("something unexpected happened", errMsg)
require.Equal(t, fmt.Sprintf("something unexpected happened; %s",
errMsg),
msg,
fmt.Sprintf("Should have formatted the error message of ABCI Log. tc #%d", i))
// ABCI Log msg error
msg = AppendMsgToErr("something unexpected happened", abciLog)
msgIdx := mustGetMsgIndex(abciLog)
require.Equal(t, fmt.Sprintf("%s%s; %s}",
abciLog[:msgIdx],
"something unexpected happened",
abciLog[msgIdx:len(abciLog)-1]),
msg,
fmt.Sprintf("Should have formatted the error message of ABCI Log. tc #%d", i))
}
}