初始化项目
This commit is contained in:
64
internal/pkg/errs/http_respone.go
Normal file
64
internal/pkg/errs/http_respone.go
Normal file
@@ -0,0 +1,64 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user