From 60340a749b76f66d2e4228fb6843e17a4996021f Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Tue, 25 Jan 2022 00:40:50 +0300 Subject: [PATCH] errors: fix MarshalJSON func Signed-off-by: Vasiliy Tolstov --- errors/errors.go | 15 ++++++++++++++- errors/errors_test.go | 9 +++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/errors/errors.go b/errors/errors.go index 486ae049..2ca8d59e 100644 --- a/errors/errors.go +++ b/errors/errors.go @@ -3,6 +3,7 @@ package errors // import "go.unistack.org/micro/v3/errors" import ( + "bytes" "encoding/json" "fmt" "net/http" @@ -261,7 +262,7 @@ func (e *Error) Reset() { // String returns error as string func (e *Error) String() string { - return fmt.Sprintf(`{"id":"%s","detail":"%s","status":"%s","code":%d}`, e.ID, e.Detail, e.Status, e.Code) + return fmt.Sprintf(`{"id":"%s","detail":"%s","status":"%s","code":%d}`, addslashes(e.ID), addslashes(e.Detail), addslashes(e.Status), e.Code) } // Marshal returns error data @@ -306,3 +307,15 @@ func (e *Error) Unmarshal(data []byte) error { } return nil } + +func addslashes(str string) string { + var buf bytes.Buffer + for _, char := range str { + switch char { + case '\'', '"', '\\': + buf.WriteRune('\\') + } + buf.WriteRune(char) + } + return buf.String() +} diff --git a/errors/errors_test.go b/errors/errors_test.go index ae4d7a96..85a5a3d3 100644 --- a/errors/errors_test.go +++ b/errors/errors_test.go @@ -1,12 +1,21 @@ package errors import ( + "encoding/json" er "errors" "fmt" "net/http" "testing" ) +func TestMarshalJSON(t *testing.T) { + e := InternalServerError("id", "err: %v", fmt.Errorf("err: %v", `xxx: "UNIX_TIMESTAMP": invalid identifier`)) + _, err := json.Marshal(e) + if err != nil { + t.Fatal(err) + } +} + func TestEmpty(t *testing.T) { msg := "test" var err *Error