support error customization
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user