errors: fix MarshalJSON func

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2022-01-25 00:40:50 +03:00
parent 8546140e22
commit 60340a749b
2 changed files with 23 additions and 1 deletions

View File

@ -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()
}

View File

@ -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