Skip to content

Commit

Permalink
Merge pull request #339 from iov-one/feature/examples-blog-error-refa…
Browse files Browse the repository at this point in the history
…ctor

Global error refactor and docs
  • Loading branch information
ethanfrey authored Feb 22, 2019
2 parents 26e6007 + 151e6a1 commit 28a0cfc
Show file tree
Hide file tree
Showing 72 changed files with 353 additions and 1,037 deletions.
13 changes: 5 additions & 8 deletions abci_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,11 @@ func TestCreateErrorResult(t *testing.T) {
msg string
code uint32
}{
{errors.NormalizePanic("stdlib"), "internal", errors.CodeInternalErr},
{fmt.Errorf("base"), "base", errors.CodeInternalErr},
{pkerr.New("dave"), "dave", errors.CodeInternalErr},
{errors.Wrap(fmt.Errorf("demo"), "wrapped"), "wrapped: demo", errors.CodeInternalErr},
{errors.New(fmt.Errorf("stdlib").Error(), 5), "stdlib", 5},
{errors.New("nonce", errors.CodeUnauthorized), "nonce", errors.CodeUnauthorized},
{errors.WithCode(fmt.Errorf("no sender"), errors.CodeUnrecognizedAddress), "no sender", errors.CodeUnrecognizedAddress},
{errors.ErrDecoding(), errors.ErrDecoding().Error(), errors.CodeTxParseError},
{errors.NormalizePanic("stdlib"), "internal", errors.ErrInternal.ABCICode()},
{fmt.Errorf("base"), "base", errors.ErrInternal.ABCICode()},
{pkerr.New("dave"), "dave", errors.ErrInternal.ABCICode()},
{errors.Wrap(fmt.Errorf("demo"), "wrapped"), "wrapped: demo", errors.ErrInternal.ABCICode()},
{errors.ErrInvalidInput.New("unable to decode"), errors.ErrInvalidInput.New("unable to decode").Error(), errors.ErrInvalidInput.ABCICode()},
}

for i, tc := range cases {
Expand Down
4 changes: 2 additions & 2 deletions app/commit.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,11 @@ func loadChainID(kv weave.KVStore) string {
// Returns error if already set, or invalid name
func saveChainID(kv weave.KVStore, chainID string) error {
if !weave.IsValidChainID(chainID) {
return errors.ErrInvalidChainID(chainID)
return errors.ErrInvalidInput.Newf("chain id: %v", chainID)
}
k := []byte(chainIDKey)
if kv.Has(k) {
return errors.ErrModifyChainID()
return errors.ErrUnauthorized.New("can't modify chain id after genesis init")
}
kv.Set(k, []byte(chainID))
return nil
Expand Down
24 changes: 4 additions & 20 deletions app/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,6 @@ const DefaultRouterSize = 10
// isPath is the RegExp to ensure the routes make sense
var isPath = regexp.MustCompile(`^[a-zA-Z0-9_/]+$`).MatchString

// CodeNoSuchPath is an ABCI Response Codes
// Base SDK reserves 0 ~ 99. App uses 10 ~ 19
const CodeNoSuchPath uint32 = 10

var errNoSuchPath = fmt.Errorf("Path not registered")

// ErrNoSuchPath constructs an error when router doesn't know the path
func ErrNoSuchPath(path string) error {
return errors.WithLog(path, errNoSuchPath, CodeNoSuchPath)
}

// IsNoSuchPathErr checks if this is an unknown route error
func IsNoSuchPathErr(err error) bool {
return errors.IsSameError(errNoSuchPath, err)
}

// Router allows us to register many handlers with different
// paths and then direct each message to the proper handler.
//
Expand Down Expand Up @@ -82,7 +66,7 @@ func (r Router) Check(ctx weave.Context, store weave.KVStore,

msg, _ := tx.GetMsg()
if msg == nil {
return weave.CheckResult{}, errors.ErrDecoding()
return weave.CheckResult{}, errors.ErrInvalidInput.New("unable to decode")
}
path := msg.Path()
h := r.Handler(path)
Expand All @@ -95,7 +79,7 @@ func (r Router) Deliver(ctx weave.Context, store weave.KVStore,

msg, _ := tx.GetMsg()
if msg == nil {
return weave.DeliverResult{}, errors.ErrDecoding()
return weave.DeliverResult{}, errors.ErrInvalidInput.New("unable to decode")
}
path := msg.Path()
h := r.Handler(path)
Expand All @@ -114,12 +98,12 @@ var _ weave.Handler = noSuchPathHandler{}
func (h noSuchPathHandler) Check(ctx weave.Context, store weave.KVStore,
tx weave.Tx) (weave.CheckResult, error) {

return weave.CheckResult{}, ErrNoSuchPath(h.path)
return weave.CheckResult{}, errors.ErrNotFound.Newf("path: %s", h.path)
}

// Deliver always returns ErrNoSuchPath
func (h noSuchPathHandler) Deliver(ctx weave.Context, store weave.KVStore,
tx weave.Tx) (weave.DeliverResult, error) {

return weave.DeliverResult{}, ErrNoSuchPath(h.path)
return weave.DeliverResult{}, errors.ErrNotFound.Newf("path: %s", h.path)
}
7 changes: 4 additions & 3 deletions app/router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package app

import (
"fmt"
"github.com/iov-one/weave/errors"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -37,16 +38,16 @@ func TestRouter(t *testing.T) {
// check errors handler is also looked up
_, err = r.Handler(bad).Deliver(nil, nil, nil)
assert.Error(t, err)
assert.False(t, IsNoSuchPathErr(err))
assert.False(t, errors.ErrNotFound.Is(err))
assert.Equal(t, msg, err.Error())
assert.Equal(t, 2, counter.GetCount())

// make sure not found returns an error handler as well
_, err = r.Handler(missing).Deliver(nil, nil, nil)
assert.Error(t, err)
assert.True(t, IsNoSuchPathErr(err))
assert.True(t, errors.ErrNotFound.Is(err))
_, err = r.Handler(missing).Check(nil, nil, nil)
assert.Error(t, err)
assert.True(t, IsNoSuchPathErr(err))
assert.True(t, errors.ErrNotFound.Is(err))
assert.Equal(t, 2, counter.GetCount())
}
6 changes: 3 additions & 3 deletions app/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ func (s *StoreApp) parseAppState(data []byte, chainID string, init weave.Initial
var appState weave.Options
err := json.Unmarshal(data, &appState)
if err != nil {
return errors.WithCode(err, errors.CodeTxParseError)
return errors.ErrInternal.New(err.Error())
}

err = s.storeChainID(chainID)
Expand Down Expand Up @@ -215,7 +215,7 @@ func (s *StoreApp) Query(reqQuery abci.RequestQuery) (resQuery abci.ResponseQuer
path, mod := splitPath(reqQuery.Path)
qh := s.queryRouter.Handler(path)
if qh == nil {
resQuery.Code = errors.CodeUnknownRequest
resQuery.Code = errors.ErrNotFound.ABCICode()
resQuery.Log = fmt.Sprintf("Unexpected Query path: %v", reqQuery.Path)
return
}
Expand Down Expand Up @@ -279,7 +279,7 @@ func splitPath(path string) (string, string) {
func queryError(err error) abci.ResponseQuery {
return abci.ResponseQuery{
Log: err.Error(),
Code: errors.CodeInternalErr,
Code: errors.ErrInternal.ABCICode(),
}
}

Expand Down
20 changes: 10 additions & 10 deletions cmd/bnsd/x/nft/username/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,19 +74,19 @@ func (h IssueHandler) validate(ctx weave.Context, tx weave.Tx) (*IssueTokenMsg,
}
msg, ok := rmsg.(*IssueTokenMsg)
if !ok {
return nil, errors.ErrUnknownTxType(rmsg)
return nil, errors.WithType(errors.ErrInvalidMsg, rmsg)
}
if err := msg.Validate(); err != nil {
return nil, err
}
// check permissions
if h.issuer != nil {
if !h.auth.HasAddress(ctx, h.issuer) {
return nil, errors.ErrUnauthorizedLegacy()
return nil, errors.ErrUnauthorized.New("")
}
} else {
if !h.auth.HasAddress(ctx, msg.Owner) {
return nil, errors.ErrUnauthorizedLegacy()
return nil, errors.ErrUnauthorized.New("")
}
}
return msg, nil
Expand Down Expand Up @@ -122,7 +122,7 @@ func (h AddChainAddressHandler) Deliver(ctx weave.Context, store weave.KVStore,

actor := nft.FindActor(h.auth, ctx, t, nft.UpdateDetails)
if actor == nil {
return res, errors.ErrUnauthorizedLegacy()
return res, errors.ErrUnauthorized.New("")
}
allKeys := append(t.GetChainAddresses(), ChainAddress{msg.GetBlockchainID(), msg.GetAddress()})
if err := t.SetChainAddresses(actor, allKeys); err != nil {
Expand All @@ -139,7 +139,7 @@ func (h *AddChainAddressHandler) validate(ctx weave.Context, tx weave.Tx) (*AddC
}
msg, ok := rmsg.(*AddChainAddressMsg)
if !ok {
return nil, errors.ErrUnknownTxType(rmsg)
return nil, errors.WithType(errors.ErrInvalidMsg, rmsg)
}
if err := msg.Validate(); err != nil {
return nil, err
Expand Down Expand Up @@ -177,10 +177,10 @@ func (h RemoveChainAddressHandler) Deliver(ctx weave.Context, store weave.KVStor

actor := nft.FindActor(h.auth, ctx, t, nft.UpdateDetails)
if actor == nil {
return res, errors.ErrUnauthorizedLegacy()
return res, errors.ErrUnauthorized.New("")
}
if len(t.GetChainAddresses()) == 0 {
return res, nft.ErrInvalidEntry([]byte("no chain to delete"))
return res, errors.ErrInvalidInput.New("empty chain addresses")
}
obsoleteAddress := ChainAddress{msg.GetBlockchainID(), msg.GetAddress()}
newAddresses := make([]ChainAddress, 0, len(t.GetChainAddresses()))
Expand All @@ -190,7 +190,7 @@ func (h RemoveChainAddressHandler) Deliver(ctx weave.Context, store weave.KVStor
}
}
if len(newAddresses) == len(t.GetChainAddresses()) {
return res, nft.ErrInvalidEntry([]byte("requested address not registered"))
return res, errors.ErrNotFound.New("requested address not registered")
}
if err := t.SetChainAddresses(actor, newAddresses); err != nil {
return res, err
Expand All @@ -205,7 +205,7 @@ func (h *RemoveChainAddressHandler) validate(ctx weave.Context, tx weave.Tx) (*R
}
msg, ok := rmsg.(*RemoveChainAddressMsg)
if !ok {
return nil, errors.ErrUnknownTxType(rmsg)
return nil, errors.WithType(errors.ErrInvalidMsg, rmsg)
}
if err := msg.Validate(); err != nil {
return nil, err
Expand All @@ -219,7 +219,7 @@ func loadToken(h tokenHandler, store weave.KVStore, id []byte) (orm.Object, Toke
case err != nil:
return nil, nil, err
case o == nil:
return nil, nil, nft.ErrUnknownID(id)
return nil, nil, errors.ErrNotFound.Newf("username %s", nft.PrintableID(id))
}
t, e := AsUsername(o)
return o, t, e
Expand Down
12 changes: 6 additions & 6 deletions cmd/bnsd/x/nft/username/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func (u *UsernameToken) GetChainAddresses() []ChainAddress {
func (u *UsernameToken) SetChainAddresses(actor weave.Address, newAddresses []ChainAddress) error {
dup := containsDuplicateChains(newAddresses)
if dup != nil {
return nft.ErrDuplicateEntry(dup)
return errors.ErrDuplicate.Newf("chain %s", nft.PrintableID(dup))
}
u.Details = &TokenDetails{Addresses: newAddresses}
return nil
Expand Down Expand Up @@ -81,11 +81,11 @@ func (t *TokenDetails) Clone() *TokenDetails {

func (t *TokenDetails) Validate() error {
if t == nil {
return errors.ErrInternalLegacy("must not be nil")
return errors.ErrInternal.New("token details must not be nil")
}
dup := containsDuplicateChains(t.Addresses)
if dup != nil {
return nft.ErrDuplicateEntry(dup)
return errors.ErrDuplicate.Newf("chain %s", nft.PrintableID(dup))
}
for _, k := range t.Addresses {
if err := k.Validate(); err != nil {
Expand Down Expand Up @@ -113,10 +113,10 @@ func (p ChainAddress) Equals(o ChainAddress) bool {

func (p *ChainAddress) Validate() error {
if !validBlockchainID(p.BlockchainID) {
return nft.ErrInvalidID(p.BlockchainID)
return errors.ErrInvalidInput.Newf("id: %s", nft.PrintableID(p.BlockchainID))
}
if n := len(p.Address); n < 2 || n > 50 {
return nft.ErrInvalidLength()
return errors.ErrInvalidInput.Newf("address length: %s", p.Address)
}
return nil
}
Expand All @@ -128,7 +128,7 @@ func AsUsername(obj orm.Object) (Token, error) {
}
x, ok := obj.Value().(*UsernameToken)
if !ok {
return nil, nft.ErrUnsupportedTokenType()
return nil, errors.ErrInvalidInput.New(nft.UnsupportedTokenType)
}
return x, nil
}
4 changes: 2 additions & 2 deletions cmd/bnsd/x/nft/username/msg.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,10 @@ func (m *RemoveChainAddressMsg) Validate() error {

func validateID(id []byte) error {
if id == nil {
return errors.ErrInternalLegacy("must not be nil")
return errors.ErrInternal.New("must not be nil")
}
if !isValidID(string(id)) {
return nft.ErrInvalidID(id)
return errors.ErrInvalidInput.Newf("id: %s", nft.PrintableID(id))
}
return nil
}
7 changes: 4 additions & 3 deletions conditions.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ func NewCondition(ext, typ string, data []byte) Condition {
func (c Condition) Parse() (string, string, []byte, error) {
chunks := perm.FindSubmatch(c)
if len(chunks) == 0 {
return "", "", nil, errors.ErrUnrecognizedCondition(c)
return "", "", nil, errors.ErrInvalidInput.Newf("condition: %X", []byte(c))

}
// returns [all, match1, match2, match3]
return string(chunks[1]), string(chunks[2]), chunks[3], nil
Expand Down Expand Up @@ -68,7 +69,7 @@ func (c Condition) String() string {
// Validate returns an error if the Condition is not the proper format
func (c Condition) Validate() error {
if !perm.Match(c) {
return errors.ErrUnrecognizedCondition(c)
return errors.ErrInvalidInput.Newf("condition: %X", []byte(c))
}
return nil
}
Expand Down Expand Up @@ -109,7 +110,7 @@ func (a Address) String() string {
// Validate returns an error if the address is not the valid size
func (a Address) Validate() error {
if len(a) != AddressLength {
return errors.ErrUnrecognizedAddress(a)
return errors.ErrInvalidInput.Newf("address: %v", a)
}
return nil
}
Expand Down
Loading

0 comments on commit 28a0cfc

Please sign in to comment.