Merge pull request #84 from unistack-org/errors_marshal

errors: fix MarshalJSON func
This commit is contained in:
Василий Толстов 2022-01-25 00:41:10 +03:00 committed by GitHub
commit 58f03d05e7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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