diff --git a/types/result.go b/types/result.go index 78cea710c..6ebad8ab2 100644 --- a/types/result.go +++ b/types/result.go @@ -39,9 +39,9 @@ func (r ResponseCommit) Error() string { func fmtError(code CodeType, log string) string { codeAsStr, ok := code2string[code] if ok { - return fmt.Sprintf("%s (%v): %s", codeAsStr, code, log) + return fmt.Sprintf("%s (%d): %s", codeAsStr, code, log) } else { - return fmt.Sprintf("Unknown error (%v): %s", code, log) + return fmt.Sprintf("Unknown error (%d): %s", code, log) } } @@ -69,3 +69,13 @@ func (r *ResponseQuery) Result() *ResultQuery { Log: r.Log, } } + +// IsErr returns true if Code is something other than OK. +func (r *ResultQuery) IsErr() bool { + return r.Code != CodeType_OK +} + +// Error implements error interface by formatting result as string. +func (r *ResultQuery) Error() string { + return fmtError(r.Code, r.Log) +} diff --git a/types/result_test.go b/types/result_test.go new file mode 100644 index 000000000..14f334c49 --- /dev/null +++ b/types/result_test.go @@ -0,0 +1,76 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestResultQuery(t *testing.T) { + orig := &ResponseQuery{ + Code: CodeType_OK, + Index: 0, + Key: []byte("hello"), + Value: []byte("world"), + Height: 1, + } + res := orig.Result() + assert.False(t, res.IsErr()) + + orig = &ResponseQuery{ + Code: CodeType_BadNonce, + Index: 0, + Key: []byte("hello"), + Value: []byte("world"), + Height: 1, + Log: "bad", + } + res = orig.Result() + assert.True(t, res.IsErr()) + assert.Equal(t, "Error bad nonce (3): bad", res.Error()) +} + +func TestResponseDeliverTx(t *testing.T) { + res := ResponseDeliverTx{ + Code: CodeType_OK, + Data: []byte("Victor Mancha"), + } + assert.False(t, res.IsErr()) + + res = ResponseDeliverTx{ + Code: CodeType_InternalError, + Log: "bad", + } + assert.True(t, res.IsErr()) + assert.Equal(t, "Internal error (1): bad", res.Error()) +} + +func TestResponseCheckTx(t *testing.T) { + res := ResponseCheckTx{ + Code: CodeType_OK, + Data: []byte("Talos"), + } + assert.False(t, res.IsErr()) + + res = ResponseCheckTx{ + Code: CodeType_InternalError, + Log: "bad", + } + assert.True(t, res.IsErr()) + assert.Equal(t, "Internal error (1): bad", res.Error()) +} + +func TestResponseCommit(t *testing.T) { + res := ResponseCommit{ + Code: CodeType_OK, + Data: []byte("Old Lace"), + } + assert.False(t, res.IsErr()) + + res = ResponseCommit{ + Code: CodeType_Unauthorized, + Log: "bad", + } + assert.True(t, res.IsErr()) + assert.Equal(t, "Unauthorized (4): bad", res.Error()) +}