mirror of
https://github.com/yusing/godoxy.git
synced 2026-04-27 11:17:29 +02:00
improved api error handling
This commit is contained in:
@@ -12,23 +12,22 @@ import (
|
||||
// http.StatusInternalServerError is used.
|
||||
//
|
||||
// The error is only logged but not returned to the client.
|
||||
func HandleErr(w http.ResponseWriter, r *http.Request, origErr error, code ...int) {
|
||||
if origErr == nil {
|
||||
func HandleErr(w http.ResponseWriter, r *http.Request, err error, code ...int) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
LogError(r).Msg(origErr.Error())
|
||||
statusCode := http.StatusInternalServerError
|
||||
if len(code) > 0 {
|
||||
statusCode = code[0]
|
||||
LogError(r).Msg(err.Error())
|
||||
if len(code) == 0 {
|
||||
code = []int{http.StatusInternalServerError}
|
||||
}
|
||||
http.Error(w, http.StatusText(statusCode), statusCode)
|
||||
http.Error(w, http.StatusText(code[0]), code[0])
|
||||
}
|
||||
|
||||
func RespondError(w http.ResponseWriter, err error, code ...int) {
|
||||
if len(code) > 0 {
|
||||
w.WriteHeader(code[0])
|
||||
if len(code) == 0 {
|
||||
code = []int{http.StatusBadRequest}
|
||||
}
|
||||
WriteBody(w, []byte(ansi.StripANSI(err.Error())))
|
||||
http.Error(w, ansi.StripANSI(err.Error()), code[0])
|
||||
}
|
||||
|
||||
func ErrMissingKey(k string) error {
|
||||
|
||||
@@ -8,9 +8,10 @@ import (
|
||||
)
|
||||
|
||||
func reqLogger(r *http.Request, level zerolog.Level) *zerolog.Event {
|
||||
return logging.WithLevel(level).Str("module", "api").
|
||||
Str("method", r.Method).
|
||||
Str("path", r.RequestURI)
|
||||
return logging.WithLevel(level).
|
||||
Str("module", "api").
|
||||
Str("remote", r.RemoteAddr).
|
||||
Str("uri", r.Method+" "+r.RequestURI)
|
||||
}
|
||||
|
||||
func LogError(r *http.Request) *zerolog.Event { return reqLogger(r, zerolog.ErrorLevel) }
|
||||
|
||||
Reference in New Issue
Block a user