errors: fix MarshalJSON func #84

Merged
vtolstov merged 1 commits from errors_marshal into master 2022-01-25 00:41:10 +03:00
2 changed files with 23 additions and 1 deletions

View File

@ -3,6 +3,7 @@
package errors // import "go.unistack.org/micro/v3/errors" package errors // import "go.unistack.org/micro/v3/errors"
import ( import (
"bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
@ -261,7 +262,7 @@ func (e *Error) Reset() {
// String returns error as string // String returns error as string
func (e *Error) String() 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 // Marshal returns error data
@ -306,3 +307,15 @@ func (e *Error) Unmarshal(data []byte) error {
} }
return nil 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 package errors
import ( import (
"encoding/json"
er "errors" er "errors"
"fmt" "fmt"
"net/http" "net/http"
"testing" "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) { func TestEmpty(t *testing.T) {
msg := "test" msg := "test"
var err *Error var err *Error