Files
novatask/internal/pkg/errs/http_respone.go
2024-12-05 20:51:35 +08:00

65 lines
1.2 KiB
Go

package errs
import (
"context"
"github.com/zeromicro/go-zero/rest/httpx"
"net/http"
"os"
"strings"
)
var debug bool
func init() {
if strings.ToLower(os.Getenv("VANS_API_DEBUG")) == "on" {
debug = true
}
httpx.SetErrorHandlerCtx(ErrorHandleCtx)
httpx.SetErrorHandler(ErrorHandle)
}
func SetDebug(d bool) {
debug = d
}
func ErrorHandle(err error) (int, any) {
return ErrorHandleCtx(context.Background(), err)
}
func ErrorHandleCtx(ctx context.Context, err error) (int, any) {
code := http.StatusBadRequest
reason := ErrInternalServer
var msg string
if ec, ok := err.(interface{ Code() int }); ok {
code = ec.Code()
}
if ec, ok := err.(interface{ Message() string }); ok {
msg = ec.Message()
} else {
msg = err.Error()
}
if ec, ok := err.(interface{ Reason() Reason }); ok {
reason = ec.Reason()
}
var errMsg string
if reason < ErrUnknownLogicError && reason != ErrSucceed {
errMsg = msg
msg = "system error"
}
body := map[string]any{
"code": reason,
"message": msg,
}
if errMsg != "" && debug {
body["err"] = errMsg
}
if ec, ok := err.(interface{ Metadata() any }); ok {
if md := ec.Metadata(); md != nil {
body["metadata"] = md
}
}
return code, body
}