Skip to content

Commit

Permalink
More explicit error on empty JSON bodies (#459)
Browse files Browse the repository at this point in the history
Return a more understandable error when the JSON codec attempts to
unmarshal an empty body.

Fixes #452.
  • Loading branch information
akshayjshah authored Feb 14, 2023
1 parent e8304e7 commit 8732471
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
4 changes: 4 additions & 0 deletions codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package connect

import (
"errors"
"fmt"

"google.golang.org/protobuf/encoding/protojson"
Expand Down Expand Up @@ -93,6 +94,9 @@ func (c *protoJSONCodec) Unmarshal(binary []byte, message any) error {
if !ok {
return errNotProto(message)
}
if len(binary) == 0 {
return errors.New("zero-length payload is not a valid JSON object")
}
var options protojson.UnmarshalOptions
return options.Unmarshal(binary, protoMessage)
}
Expand Down
37 changes: 37 additions & 0 deletions codec_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright 2021-2023 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package connect

import (
"strings"
"testing"

"connectrpc.com/connect/internal/assert"
"google.golang.org/protobuf/types/known/emptypb"
)

func TestJSONCodec(t *testing.T) {
t.Parallel()

var empty emptypb.Empty
codec := &protoJSONCodec{name: "json"}
err := codec.Unmarshal([]byte{}, &empty)
assert.NotNil(t, err)
assert.True(
t,
strings.Contains(err.Error(), "valid JSON"),
assert.Sprintf(`error message should explain that "" is not a valid JSON object`),
)
}

0 comments on commit 8732471

Please sign in to comment.