diff --git a/message.go b/message.go index f37e0e3..9942f06 100644 --- a/message.go +++ b/message.go @@ -6,7 +6,15 @@ import ( ) func (m *OSCMessage) ToBytes() ([]byte, error) { - //TODO(jwetzell): add error handling + + if len(m.Address) == 0 { + return nil, errors.New("OSC Message must have an address") + } + + if m.Address[0] != '/' { + return nil, errors.New("OSC Message address must start with /") + } + oscBuffer := []byte{} oscBuffer = append(oscBuffer, stringToOSCBytes(m.Address)...) @@ -18,7 +26,6 @@ func (m *OSCMessage) ToBytes() ([]byte, error) { for _, arg := range m.Args { sb.WriteString(arg.Type) } - oscBuffer = append(oscBuffer, stringToOSCBytes(sb.String())...) argsBuffer, err := argsToBuffer(m.Args) if err != nil { diff --git a/message_test.go b/message_test.go index e163f0e..5000488 100644 --- a/message_test.go +++ b/message_test.go @@ -142,6 +142,47 @@ func TestGoodOSCMessageEncoding(t *testing.T) { } +func TestBadOSCMessageEncoding(t *testing.T) { + testCases := []struct { + name string + message *OSCMessage + errorString string + }{ + { + name: "empty message", + message: &OSCMessage{}, + errorString: "OSC Message must have an address", + }, + { + name: "address does not start with /", + message: &OSCMessage{Address: "hello"}, + errorString: "OSC Message address must start with /", + }, + { + name: "arg with unsupported type", + message: &OSCMessage{ + Address: "/hello", + Args: []OSCArg{{Type: "x", Value: "unsupported"}}, + }, + errorString: "unsupported OSC argument type: x", + }, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + got, err := testCase.message.ToBytes() + + if err == nil { + t.Fatalf("OSCMessage.ToBytes() expected to fail but got: %+v", got) + } + + if err.Error() != testCase.errorString { + t.Fatalf("OSCMessage.ToBytes() got error '%s', expected '%s'", err.Error(), testCase.errorString) + } + }) + } +} + func TestGoodOSCMessageDecoding(t *testing.T) { testCases := []struct { name string diff --git a/osc.go b/osc.go index e0be749..4e403cd 100644 --- a/osc.go +++ b/osc.go @@ -240,7 +240,7 @@ func argsToBuffer(args []OSCArg) ([]byte, error) { fmt.Println("OSC arg had float type but non-float value.") } default: - fmt.Printf("unhandled osc type: %s.\n", oscType) + return nil, fmt.Errorf("unsupported OSC argument type: %s", oscType) } } return argBuffers, nil