Skip to content

Commit

Permalink
fix(bindnode): more helpful error message for enum value footgun
Browse files Browse the repository at this point in the history
Fixes: #348
  • Loading branch information
rvagg committed May 25, 2022
1 parent e01280e commit ac672fa
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
38 changes: 38 additions & 0 deletions node/bindnode/api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package bindnode_test

import (
"testing"

qt "github.com/frankban/quicktest"
"github.com/ipld/go-ipld-prime"
"github.com/ipld/go-ipld-prime/codec/dagcbor"
"github.com/ipld/go-ipld-prime/node/bindnode"
)

func TestEnumError(t *testing.T) {
type Action string
const (
ActionPresent = Action("p")
ActionMissing = Action("m")
)
type S struct{ Action Action }

schema := `
type S struct {
Action Action
} representation tuple
type Action enum {
| Present ("p")
| Missing ("m")
} representation string
`

typeSystem, err := ipld.LoadSchemaBytes([]byte(schema))
qt.Assert(t, err, qt.IsNil)
schemaType := typeSystem.TypeByName("S")

node := bindnode.Wrap(&S{Action: ActionPresent}, schemaType).Representation()
_, err = ipld.Encode(node, dagcbor.Encode)
qt.Assert(t, err, qt.IsNotNil)
qt.Assert(t, err.Error(), qt.Equals, `AsString: "p" is not a valid member of enum Action (bindnode works at the type level; did you mean "Present"?)`)
}
6 changes: 6 additions & 0 deletions node/bindnode/repr.go
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,12 @@ func (w *_nodeRepr) AsString() (string, error) {
return s, nil
}
}
for k, v := range stg {
// a programming error? we may have the enum string value rather than the type
if v == s {
return "", fmt.Errorf("AsString: %q is not a valid member of enum %s (bindnode works at the type level; did you mean %q?)", s, w.schemaType.Name(), k)
}
}
return "", fmt.Errorf("AsString: %q is not a valid member of enum %s", s, w.schemaType.Name())
default:
return (*_node)(w).AsString()
Expand Down

0 comments on commit ac672fa

Please sign in to comment.