u
This commit is contained in:
1 parent
69d03709ba
commit
44fb48ef6a
9 files changed
+625
-25
No files matched your search
@@ -1,29 +1,45 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"base-go-v2/internal/errs"
|
||||
"base-go-v2/internal/logx"
|
||||
"base-go-v2/internal/reponse"
|
||||
"base-go-v2/internal/router"
|
||||
"errors"
|
||||
"runtime/debug"
|
||||
)
|
||||
|
||||
func ErrorMiddleware() router.HandlerFunc {
|
||||
// 可扩展的业务错误类型列表
|
||||
businessErrors := []interface{}{
|
||||
(*errs.ValidationError)(nil),
|
||||
// (*errs.BusinessError)(nil),
|
||||
// (*errs.AuthError)(nil),
|
||||
}
|
||||
|
||||
return func(c *router.Context) error {
|
||||
err := c.Next()
|
||||
|
||||
if err != nil {
|
||||
stack := string(debug.Stack())
|
||||
|
||||
logx.Logger.Error("请求错误",
|
||||
logx.String("path", string(c.RequestCtx.Path())),
|
||||
logx.String("method", string(c.RequestCtx.Method())),
|
||||
logx.String("error", err.Error()),
|
||||
logx.String("stack", stack),
|
||||
)
|
||||
|
||||
return response.Error(c).Message(err.Error()).Send()
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return nil
|
||||
// 判断是否属于业务错误
|
||||
for _, be := range businessErrors {
|
||||
// be 是 nil 指针类型
|
||||
if errors.As(err, &be) {
|
||||
// 业务错误,不记录日志
|
||||
return response.Error(c).Message(err.Error()).Send()
|
||||
}
|
||||
}
|
||||
|
||||
// 系统错误,记录日志
|
||||
stack := string(debug.Stack())
|
||||
logx.Logger.Error("请求错误",
|
||||
logx.String("path", string(c.RequestCtx.Path())),
|
||||
logx.String("method", string(c.RequestCtx.Method())),
|
||||
logx.String("error", err.Error()),
|
||||
logx.String("stack", stack),
|
||||
)
|
||||
return response.Error(c).Message("服务器内部错误").Send()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user