From 22d873f6bd3a82a0244f7b88a9c7b786be8e8e23 Mon Sep 17 00:00:00 2001 From: chen-mou <42209673+chen-mou@users.noreply.github.com> Date: Fri, 26 Sep 2025 16:07:47 +0800 Subject: [PATCH] fix(gerror): Fixed serialization failure issue when gerror.Error text field contains quote symbols (#4449) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 如果调用internal 下的json.Marshal时 参数如果是gerror.Error 并且 字段中带有符号" 会导致序列化失败 原因是原gerror.Error 的MarshalJson方法只对字符串做了简单的处理 如果err.Error 返回的字符串中有符号" 这个符号会在序列化的时候被认为是字符串的终止导致序列化失败 image --------- Co-authored-by: hailaz <739476267@qq.com> --- errors/gerror/gerror_error_json.go | 6 +++++- errors/gerror/gerror_z_unit_test.go | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/errors/gerror/gerror_error_json.go b/errors/gerror/gerror_error_json.go index 5c290d7af..ae245cdd7 100644 --- a/errors/gerror/gerror_error_json.go +++ b/errors/gerror/gerror_error_json.go @@ -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()) } diff --git a/errors/gerror/gerror_z_unit_test.go b/errors/gerror/gerror_z_unit_test.go index 83acc1837..1e463d1ba 100644 --- a/errors/gerror/gerror_z_unit_test.go +++ b/errors/gerror/gerror_z_unit_test.go @@ -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) {