Skip to content

Commit d520080

Browse files
shogo82148bmoffatt
andauthored
safeMarshal should escape the error message (#327)
* safeMarshal should escape the error message * add a test for safeMarshal Co-authored-by: Bryan Moffatt <bmoffatt@users.noreply.github.com>
1 parent 406b8fc commit d520080

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

lambda/invoke_loop.go

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,8 @@ import (
1313
)
1414

1515
const (
16-
serializationErrorFormat = `{"errorType": "Runtime.SerializationError", "errorMessage": "%s"}`
17-
msPerS = int64(time.Second / time.Millisecond)
18-
nsPerMS = int64(time.Millisecond / time.Nanosecond)
16+
msPerS = int64(time.Second / time.Millisecond)
17+
nsPerMS = int64(time.Millisecond / time.Nanosecond)
1918
)
2019

2120
// startRuntimeAPILoop will return an error if handling a particular invoke resulted in a non-recoverable error
@@ -103,7 +102,15 @@ func convertInvokeRequest(invoke *invoke) (*messages.InvokeRequest, error) {
103102
func safeMarshal(v interface{}) []byte {
104103
payload, err := json.Marshal(v)
105104
if err != nil {
106-
return []byte(fmt.Sprintf(serializationErrorFormat, err.Error()))
105+
v := &messages.InvokeResponse_Error{
106+
Type: "Runtime.SerializationError",
107+
Message: err.Error(),
108+
}
109+
payload, err := json.Marshal(v)
110+
if err != nil {
111+
panic(err) // never reach
112+
}
113+
return payload
107114
}
108115
return payload
109116
}

lambda/invoke_loop_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,18 @@ func TestReadPayload(t *testing.T) {
106106

107107
}
108108

109+
type invalidPayload struct{}
110+
111+
func (invalidPayload) MarshalJSON() ([]byte, error) {
112+
return nil, errors.New(`some error that contains '"'`)
113+
}
114+
115+
func TestSafeMarshal_SerializationError(t *testing.T) {
116+
payload := safeMarshal(invalidPayload{})
117+
want := `{"errorMessage":"json: error calling MarshalJSON for type lambda.invalidPayload: some error that contains '\"'","errorType":"Runtime.SerializationError"}`
118+
assert.Equal(t, want, string(payload))
119+
}
120+
109121
type requestRecord struct {
110122
nGets int
111123
nPosts int

0 commit comments

Comments
 (0)