Skip to content

Commit

Permalink
Don't panic; return an error.
Browse files Browse the repository at this point in the history
  • Loading branch information
scr-oath committed Dec 11, 2024
1 parent e916199 commit 8444c5c
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 11 deletions.
2 changes: 1 addition & 1 deletion openrtb_ext/request_wrapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -1278,7 +1278,7 @@ func (re *RegExt) unmarshal(extJson json.RawMessage) error {

gpcJson, hasGPC := re.ext[gpcKey]
if hasGPC && gpcJson != nil {
jsonutil.ParseIntoString(gpcJson, &re.gpc)
return jsonutil.ParseIntoString(gpcJson, &re.gpc)
}

return nil
Expand Down
7 changes: 5 additions & 2 deletions util/jsonutil/forcestring.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
package jsonutil

import (
"errors"

"github.com/prebid/prebid-server/v3/util/ptrutil"
"github.com/tidwall/gjson"
)

// ParseIntoString Parse json bytes into a string pointer
func ParseIntoString(b []byte, ppString **string) {
func ParseIntoString(b []byte, ppString **string) error {
if ppString == nil {
panic("ppString is nil")
return errors.New("ppString is nil")
}
result := gjson.ParseBytes(b)
if result.Exists() && result.Raw != `null` {
*ppString = ptrutil.ToPtr(result.String())
}
return nil
}
20 changes: 12 additions & 8 deletions util/jsonutil/forcestring_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import (

func Test_ParseIntoString(t *testing.T) {
tests := []struct {
name string
b []byte
want *string
name string
b []byte
want *string
wantErr bool
}{
{
name: "empty",
Expand Down Expand Up @@ -44,14 +45,17 @@ func Test_ParseIntoString(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var got *string
ParseIntoString(tt.b, &got)
err := ParseIntoString(tt.b, &got)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}
}

func Test_ParseIntoStringPanic(t *testing.T) {
assert.Panics(t, func() {
ParseIntoString([]byte(`"123"`), nil)
})
func Test_ParseIntoNilStringError(t *testing.T) {
assert.Error(t, ParseIntoString([]byte(`"123"`), nil))
}

0 comments on commit 8444c5c

Please sign in to comment.