add error handle tests

This commit is contained in:
kevin
2020-11-17 18:04:48 +08:00
parent abcb28e506
commit 9592639cb4
2 changed files with 72 additions and 13 deletions

View File

@@ -9,16 +9,27 @@ import (
)
var (
errorHandler = defaultErrorHandler
errorHandler func(error) (int, interface{})
lock sync.RWMutex
)
func Error(w http.ResponseWriter, err error) {
lock.RLock()
code, body := errorHandler(err)
handler := errorHandler
lock.RUnlock()
WriteJson(w, code, body)
if handler == nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
code, body := errorHandler(err)
e, ok := body.(error)
if ok {
http.Error(w, e.Error(), code)
} else {
WriteJson(w, code, body)
}
}
func Ok(w http.ResponseWriter) {
@@ -51,7 +62,3 @@ 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
}