Skip to content

Commit

Permalink
support error customization
Browse files Browse the repository at this point in the history
  • Loading branch information
kevwan committed Nov 17, 2020
1 parent a92f655 commit abcb28e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ require (
golang.org/x/tools v0.0.0-20200410132612-ae9902aceb98 // indirect
google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f // indirect
google.golang.org/grpc v1.29.1
google.golang.org/protobuf v1.25.0 // indirect
google.golang.org/protobuf v1.25.0
gopkg.in/cheggaaa/pb.v1 v1.0.28
gopkg.in/h2non/gock.v1 v1.0.15
gopkg.in/yaml.v2 v2.3.0
Expand Down
22 changes: 21 additions & 1 deletion rest/httpx/responses.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,22 @@ package httpx
import (
"encoding/json"
"net/http"
"sync"

"github.com/tal-tech/go-zero/core/logx"
)

var (
errorHandler = defaultErrorHandler
lock sync.RWMutex
)

func Error(w http.ResponseWriter, err error) {
http.Error(w, err.Error(), http.StatusBadRequest)
lock.RLock()
code, body := errorHandler(err)
lock.RUnlock()

WriteJson(w, code, body)
}

func Ok(w http.ResponseWriter) {
Expand All @@ -19,6 +29,12 @@ func OkJson(w http.ResponseWriter, v interface{}) {
WriteJson(w, http.StatusOK, v)
}

func SetErrorHandler(handler func(error) (int, interface{})) {
lock.Lock()
defer lock.Unlock()
errorHandler = handler
}

func WriteJson(w http.ResponseWriter, code int, v interface{}) {
w.Header().Set(ContentType, ApplicationJson)
w.WriteHeader(code)
Expand All @@ -35,3 +51,7 @@ func WriteJson(w http.ResponseWriter, code int, v interface{}) {
logx.Errorf("actual bytes: %d, written bytes: %d", len(bs), n)
}
}

func defaultErrorHandler(err error) (int, interface{}) {
return http.StatusBadRequest, err
}

0 comments on commit abcb28e

Please sign in to comment.