Commit bfb8b49e authored by Will Scott's avatar Will Scott

Return error rather than panic

parent a96a7f02
......@@ -2,6 +2,7 @@ package ipld
import (
"fmt"
"strings"
)
// ErrWrongKind may be returned from functions on the Node interface when
......@@ -152,6 +153,15 @@ func (e ErrIteratorOverread) Error() string {
type ErrCannotBeNull struct{} // Review: arguably either ErrInvalidKindForNodePrototype.
type ErrMissingRequiredField struct{} // only possible for typed nodes -- specifically, struct types.
// ErrMissingRequiredField is returned when calling 'Finish' on a NodeAssembler
// for a Struct that has not has all required fields set.
type ErrMissingRequiredField struct {
Missing []string
}
func (e ErrMissingRequiredField) Error() string {
return "missing required fields: " + strings.Join(e.Missing, ",")
}
type ErrListOverrun struct{} // only possible for typed nodes -- specifically, struct types with list (aka tuple) representations.
type ErrInvalidUnionDiscriminant struct{} // only possible for typed nodes -- specifically, union types.
......@@ -508,7 +508,15 @@ func (g structBuilderGenerator) emitMapAssemblerMethods(w io.Writer) {
panic("invalid state: Finish cannot be called on an assembler that's already finished")
}
if ma.s & fieldBits__{{ $type | TypeSymbol }}_sufficient != fieldBits__{{ $type | TypeSymbol }}_sufficient {
panic("invalid state: Not all required fields set")
err := ipld.ErrMissingRequiredField{Missing: make([]string, 0)}
{{- range $i, $field := .Type.Fields }}
{{- if not $field.IsMaybe}}
if ma.s & fieldBit__{{ $type | TypeSymbol }}_{{ $field | FieldSymbolUpper }} == 0 {
err.Missing = append(err.Missing, "{{ $field.Name }}")
}
{{- end}}
{{- end}}
return err
}
ma.state = maState_finished
*ma.m = schema.Maybe_Value
......
......@@ -187,15 +187,10 @@ func TestStructsContainingMaybe(t *testing.T) {
}
v.AssignString("v1")
shouldPanicOnBuild := func(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Errorf("The code did not panic")
}
}()
_ = b.Build()
err = mb.Finish()
if _, ok := err.(ipld.ErrMissingRequiredField); !ok {
t.Fatalf("Expected error for missing field, got %v", err)
}
shouldPanicOnBuild(t)
})
})
})
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment