fix(gerror): Fixed serialization failure issue when gerror.Error text field contains quote symbols (#4449)

如果调用internal 下的json.Marshal时 参数如果是gerror.Error 并且 字段中带有符号" 会导致序列化失败
原因是原gerror.Error 的MarshalJson方法只对字符串做了简单的处理 如果err.Error 返回的字符串中有符号"
这个符号会在序列化的时候被认为是字符串的终止导致序列化失败
<img width="854" height="186" alt="image"
src="https://github.com/user-attachments/assets/9a1e6d72-943f-41ad-a487-8a3c0f28f9f0"
/>

---------

Co-authored-by: hailaz <739476267@qq.com>
This commit is contained in:
chen-mou
2025-09-26 16:07:47 +08:00
committed by GitHub
parent b60b04e27a
commit 22d873f6bd
2 changed files with 18 additions and 1 deletions

View File

@ -6,8 +6,12 @@
package gerror
import (
"encoding/json"
)
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
// Note that do not use pointer as its receiver here.
func (err Error) MarshalJSON() ([]byte, error) {
return []byte(`"` + err.Error() + `"`), nil
return json.Marshal(err.Error())
}

View File

@ -395,6 +395,19 @@ func Test_Json(t *testing.T) {
t.Assert(e, nil)
t.Assert(string(b), `"2: 1"`)
})
gtest.C(t, func(t *gtest.T) {
errNormal := gerror.New("test")
b, e := json.Marshal(errNormal)
t.Assert(e, nil)
t.Assert(string(b), `"test"`)
})
gtest.C(t, func(t *gtest.T) {
// The string contains special characters.
errWithSign := gerror.New(`test ""`)
b, e := json.Marshal(errWithSign)
t.Assert(e, nil)
t.Assert(string(b), `"test \"\""`)
})
}
func Test_HasStack(t *testing.T) {