support error customization

master
kevin 4 years ago
parent a92f65580c
commit abcb28e506

@ -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

@ -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) {
@ -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)
@ -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
}

Loading…
Cancel
Save