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
Showing only changes of commit 60340a749b - Show all commits

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