add MarshalJSON func for lib errs (#11614)

Customize the json output with message with err.Error(). Otherwise, the wrappged message will be lost
in the final errors object.

Signed-off-by: wang yan <wangyan@vmware.com>
This commit is contained in:
Wang Yan 2020-04-15 11:30:14 +08:00 committed by GitHub
parent 5cf72e3ba4
commit 9bc96dd97a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 35 additions and 2 deletions

View File

@ -51,6 +51,17 @@ func (e *Error) StackTrace() string {
return e.Stack.frames().format()
}
// MarshalJSON ...
func (e *Error) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Code string `json:"code"`
Message string `json:"message"`
}{
Code: e.Code,
Message: e.Error(),
})
}
// WithMessage ...
func (e *Error) WithMessage(format string, v ...interface{}) *Error {
e.Message = fmt.Sprintf(format, v...)
@ -86,7 +97,7 @@ func (errs Errors) Error() string {
for _, e := range errs {
err, ok := e.(*Error)
if !ok {
err = UnknownError(e).WithMessage(e.Error())
err = UnknownError(e)
}
if err.Code == "" {
err.Code = GeneralCode

View File

@ -252,6 +252,28 @@ func (suite *ErrorTestSuite) TestCauseStd() {
suite.Equal(root, Cause(cause3))
}
func (suite *ErrorTestSuite) TestMarshalJSON() {
stdErr := errors.New("stdErr")
err := Wrap(stdErr, "root").WithCode(ConflictCode)
err2 := Wrap(err, "append message").WithCode(ConflictCode)
out, marErr := err2.MarshalJSON()
suite.Nil(marErr)
suite.Equal(`{"code":"CONFLICT","message":"append message: root: stdErr"}`, string(out))
}
func (suite *ErrorTestSuite) TestErrors() {
stdErr := errors.New("stdErr")
suite.Equal(`{"errors":[{"code":"UNKNOWN","message":"unknown: stdErr"}]}`, NewErrs(stdErr).Error())
err := Wrap(stdErr, "root").WithCode(ConflictCode)
err2 := Wrap(err, "append message").WithCode(ConflictCode)
suite.Equal(`{"errors":[{"code":"CONFLICT","message":"append message: root: stdErr"}]}`, NewErrs(err2).Error())
err = New(nil).WithCode(GeneralCode).WithMessage("internal server error")
suite.Equal(`{"errors":[{"code":"UNKNOWN","message":"internal server error"}]}`, NewErrs(err).Error())
}
func TestErrorTestSuite(t *testing.T) {
suite.Run(t, &ErrorTestSuite{})
}

View File

@ -78,7 +78,7 @@ func TestAPIError(t *testing.T) {
e := pkg_errors.New("customized error")
statusCode, payload, stacktrace = apiError(e)
assert.Equal(t, http.StatusInternalServerError, statusCode)
assert.Equal(t, `{"errors":[{"code":"UNKNOWN","message":"customized error"}]}`, payload)
assert.Equal(t, `{"errors":[{"code":"UNKNOWN","message":"unknown: customized error"}]}`, payload)
assert.Contains(t, stacktrace, ``)
}