diff --git a/src/lib/errors/errors.go b/src/lib/errors/errors.go index 6bca7eab8..12cdf7271 100644 --- a/src/lib/errors/errors.go +++ b/src/lib/errors/errors.go @@ -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 diff --git a/src/lib/errors/errors_test.go b/src/lib/errors/errors_test.go index 1fd71068a..cade87f40 100644 --- a/src/lib/errors/errors_test.go +++ b/src/lib/errors/errors_test.go @@ -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{}) } diff --git a/src/server/error/error_test.go b/src/server/error/error_test.go index f91a9a71b..33b21fb54 100644 --- a/src/server/error/error_test.go +++ b/src/server/error/error_test.go @@ -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, ``) }