Browse Source

add errorwithcode interface

tags/v0.5.5
Lunny Xiao 2 years ago
parent
commit
07d2a32dde
Signed by: lunny <xiaolunwen@gmail.com> GPG Key ID: C3B7C91B632F738A
3 changed files with 53 additions and 0 deletions
  1. +6
    -0
      error.go
  2. +9
    -0
      return.go
  3. +38
    -0
      return_test.go

+ 6
- 0
error.go View File

@@ -77,3 +77,9 @@ func Errors() HandlerFunc {
}
}
}

// ErrorWithCode descripts an error that with error code
type ErrorWithCode interface {
error
ErrorCode() int
}

+ 9
- 0
return.go View File

@@ -129,6 +129,15 @@ func Return() HandlerFunc {
encoder.Encode(map[string]string{
"err": res.Error(),
})
case ErrorWithCode:
if statusCode == 0 {
statusCode = http.StatusOK
}
ctx.WriteHeader(statusCode)
encoder.Encode(map[string]interface{}{
"err": res.Error(),
"err_code": res.ErrorCode(),
})
case error:
if statusCode == 0 {
statusCode = http.StatusOK


+ 38
- 0
return_test.go View File

@@ -163,6 +163,44 @@ func TestReturnJsonError2(t *testing.T) {
expect(t, strings.TrimSpace(buff.String()), `{"err":"error"}`)
}

type JSONErrReturn3 struct {
JSON
}

type MyError struct {
}

func (m *MyError) Error() string {
return "error"
}

func (m *MyError) ErrorCode() int {
return 1
}

func (JSONErrReturn3) Get() error {
return &MyError{}
}

func TestReturnJsonError3(t *testing.T) {
buff := bytes.NewBufferString("")
recorder := httptest.NewRecorder()
recorder.Body = buff

o := Classic()
o.Get("/", new(JSONErrReturn3))

req, err := http.NewRequest("GET", "http://localhost:8000/", nil)
if err != nil {
t.Error(err)
}

o.ServeHTTP(recorder, req)
expect(t, recorder.Code, http.StatusOK)
refute(t, len(buff.String()), 0)
expect(t, strings.TrimSpace(buff.String()), `{"err":"error","err_code":1}`)
}

type JSONReturn1 struct {
JSON
}


Loading…
Cancel
Save